閱讀526 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Apache HttpComponents Client 4.0快速入門/升級-2.POST方法訪問網頁

Apache HttpComponents Client 4.0已經發布多時,httpclient項目從commons子項目挪到了HttpComponents子項目下,httpclient3.1和 httpcilent4.0無法做到代碼向後兼容,升級比較麻煩。我在做項目之餘找時間研究了一下,寫了一套3.1與4.0對比的代碼,不求麵麵俱到,但 求簡單易懂。如果代碼用到真實項目中,還需要考慮諸如代理、Header、異常處理之類的問題。

 

Http POST方法得到www.g.cn的源碼:

import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; public class PostSample { public static void main(String[] args) throws ParseException, IOException { String url = "https://www.g.cn/"; System.out.println(url); System.out.println("Visit google using Apache commons-httpclient 3.1:"); List<NameValuePair> data3 = new ArrayList<NameValuePair>(); data3.add(new NameValuePair("username", "testuser")); data3.add(new NameValuePair("password", "testpassword")); System.out.println(post3(url, data3)); System.out.println("Visit google using Apache HttpComponents Client 4.0:"); List<BasicNameValuePair> data4 = new ArrayList<BasicNameValuePair>(); data4.add(new BasicNameValuePair("username", "testuser")); data4.add(new BasicNameValuePair("password", "testpassword")); System.out.println(post4(url, data4)); } /** 使用Apache commons-httpclient 3.1,POST方法訪問網頁 */ public static String post3(String url, List<NameValuePair> data) throws IOException { org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient(); PostMethod postMethod = new PostMethod(url); postMethod.setRequestBody(data.toArray(new NameValuePair[data.size()])); try { System.out.println("<< Response: " + httpClient.executeMethod(postMethod)); return postMethod.getResponseBodyAsString(); } finally { postMethod.releaseConnection(); } } /** 使用Apache HttpComponents Client 4.0,POST方法訪問網頁 */ private static String post4(String url, List<? extends org.apache.http.NameValuePair> data) throws ParseException, IOException { org.apache.http.client.HttpClient client = new DefaultHttpClient(); HttpPost httpost = new HttpPost(url); httpost.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8)); try { HttpResponse response = client.execute(httpost); HttpEntity entity = response.getEntity(); System.out.println("<< Response: " + response.getStatusLine()); if (entity != null) { return EntityUtils.toString(entity); } return null; } finally { client.getConnectionManager().shutdown(); } } }

當然www.g.cn不必要通過post來訪問,一般用於需要提交表單的情形。

最後更新:2017-04-02 04:00:25

  上一篇:go 跨頁投遞和Transfer的區別
  下一篇:go 百度有啊前端js框架分析(一)