寫一個小程序,模擬Http POST請求來從網站中獲取數據。使用Jsoup(http://jsoup.org/)來解析HTML。
Jsoup封裝了HttpConnection的功能,可以向服務器提交請求。但分析了目標網站(http://rapdb.dna.affrc.go.jp/tools/converter/run)的數據提交方式后,決定自己用代碼來模擬Content-type為 multipart/form-data的form表單提交。
1、HttpURLConnection :A URLConnection with support for HTTP-specific features.一個可以支持HTTP的URL連接。
connection.setRequestMethod("POST");
connection.setConnectTimeout(5 * 60 * 1000);
connection.setReadTimeout(5 * 60 * 1000);
connection.addRequestProperty(“User-Agent”, “Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36”);
connection.addRequestProperty("Content-Type", "multipart/form-data; boundary=--testsssssss");
//若需要向服務器請求數據,需要設定為true,默認為false
connection.setDoOutput(true);
//若提交為post方式,需要修改為false
connection.setUseCaches(false);
//向報務器連接
Connection.connect();
output = connection.getOutputStream();
//向服務器傳送post數據
output.write(bodyStr.getBytes());
向服務器發送請求后,服務器應該能接收到類似的數據:
POST /test HTTP/1.1 Accept-Language: zh-CN,zh;q=0.8 //connection.addestProperty設定的Http請求頭信息 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Content-Type: multipart/form-data; boundary=--testsssssss Cache-Control: no-cache Pragma: no-cache Host: localhost Connection: keep-alive //Http請求的正文大小,未手工設定,程序自動生成? Content-Length: 224 --HrOGHuIjDhR_gtUesEBnpWxVp9JH209p Content-Disposition: form-data; name="keyword" test --HrOGHuIjDhR_gtUesEBnpWxVp9JH209p Content-Disposition: form-data; name="submit" Convert --HrOGHuIjDhR_gtUesEBnpWxVp9JH209p--
2、向服務器請求數據時常用的方式:
- GET:當form提交時,請求參數拼接在URl上,使用&來分隔。 POST:提交form時,請求參數封裝在請求body中,可傳遞大批量數據。請求時數據封裝類型有很多種(http://en.wikipedia.org/wiki/Internet_media_type),常用的不多:
-
- application/x-www-form-urlencoded 默認的提交方式,同GET類似,將參數組裝成Key-value方式,用&分隔,但數據存放在body中提交
- multipart/form-data 這種方式一般用來上傳文件,或大批量數據時。
該網站的提交方式為post,MIME類型為multipart/form-data類型。需要組裝相應的數據。
該類型的數據提交時需要在HTTP請求頭中的content-type添加boundary字段,正文的數據就以該字段來區分:
//boundary為--testsssssss
connection.addRequestProperty("Content-Type", "multipart/form-data; boundary=--testsssssss");
在封裝Http請求的Body中,要以boundary來區分開各個字段:String mimeBoundary = "--testsssssss";
StringBuffer sb = new StringBuffer(); //在boundary關需添加兩個橫線 sb = sb.append("--").append(mimeBoundary); sb.append("\r\n"); sb.append("Content-Disposition: form-data; name=\"keyword\""); //提交的數據前要有兩個回車換行 sb.append("\r\n\r\n");
sb.append(queryText); sb.append("\r\n"); //第二個提交的參數 sb.append("--").append(mimeBoundary); sb.append("\r\n"); sb.append("Content-Disposition: form-data; name=\"submit\""); sb.append("\r\n\r\n"); sb.append("Convert"); sb.append("\r\n"); //body結束時 boundary前后各需添加兩上橫線,最添加添回車換行 sb.append("--").append(mimeBoundary).append("--").append("\r\n");
若提交的數據為文件或圖片類型,需要讀取文件內容。http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
3、jsoup解析數據:
jsoup解析HTML代碼的方式類似於javascript。
可以將HttpUrlConnection接收到的html字符串來組裝 Document:
Document doc = Jsoup.parse(html); //獲取html中id為tools_converter的元素 //假設html代碼如:<a id="tools_converter" href="http://localhost">測試</a> Element element = doc.getElementById("tools_converter"); //可獲取text的數據為:測試 String text = element.text(); //可獲得attr的數據為:http://localhost String attr = element.attr("href"); //也可以直接使用Jsoup封裝的HttpConnection來請求數據器: Document document = Jsoup.connect(url) .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36").get();
Jsoup提供的部分方法如下:
getElementsByTag(String):按Tag標簽來獲取:Elements divs = document.getElementsByTag("div")
getElementById(String):按id標簽來獲取:Element idEle = document.getElementById("blogId")
getElementsByClass(String):按CSS的Class名稱來獲取:Elements divs = document.getElementsByClass("redClass")
children():返回Elements,某元素的所有子元素。
child(int index):返回Element,某元素的第幾個子元素:
鏈接:
