寫一個小程序,模擬HttpPOST請求來從網站中獲取數據。使用Jsoup(http://jsoup.org/)來解析HTML。
Jsoup封裝了HttpConnection的功能,可以向服務器提交請求。但分析了目標網站(http://rapdb.dna.affrc.go.jp/tools/converter/run)的數據提交方式后,決定自己用代碼來模擬Content-type為 multipart/form-data的form表單提交。
1、HttpURLConnection:AURLConnectionwithsupportforHTTP-specificfeatures.一個可以支持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,默認為falseconnection.setDoOutput(true);//若提交為post方式,需要修改為falseconnection.setUseCaches(false);//向報務器連接Connection.connect();output = connection.getOutputStream();//向服務器傳送post數據output.write(bodyStr.getBytes());
向服務器發送請求后,服務器應該能接收到類似的數據:
POST /test HTTP/1.1Accept-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.36Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8Content-Type: multipart/form-data; boundary=--testsssssssCache-Control: no-cachePragma: no-cacheHost: localhostConnection: keep-alive//Http請求的正文大小,未手工設定,程序自動生成?Content-Length: 224--HrOGHuIjDhR_gtUesEBnpWxVp9JH209pContent-Disposition: form-data; name="keyWord"test--HrOGHuIjDhR_gtUesEBnpWxVp9JH209pContent-Disposition: form-data; name="submit"Convert--HrOGHuIjDhR_gtUesEBnpWxVp9JH209p--
2、向服務器請求數據時常用的方式:
該網站的提交方式為post,MIME類型為multipart/form-data類型。需要組裝相應的數據。
該類型的數據提交時需要在HTTP請求頭中的content-type添加boundary字段,正文的數據就以該字段來區分:
//boundary為--testsssssssconnection.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://localhostString 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,某元素的第幾個子元素:
參考Jsoup API
鏈接:
JDK中的URLConnection參數詳解
新聞熱點
疑難解答