栏目:Web开发 作者:admin 日期:2015-05-02 评论:0 点击: 5,878 次
HttpClient的用法十分简单,先给大家看一个小例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; public class Test { public static void main(String[] args) { HttpClient httpClient = new HttpClient(); HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams(); // 设置连接超时时间(单位毫秒) managerParams.setConnectionTimeout(30000); // 设置读数据超时时间(单位毫秒) managerParams.setSoTimeout(120000); String url = "localhost"; PostMethod postMethod = new PostMethod(url); Header header = new Header(); header.setName("Cookie"); header.setValue("cookie"); header.setName("Refer"); header.setValue("refer"); postMethod.setRequestHeader(header); String strResponse = null; int statusCode=-1; try { statusCode= httpClient.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { throw new IllegalStateException("Method failed: "+ postMethod.getStatusLine()); } strResponse = postMethod.getResponseBodyAsString(); } catch (Exception ex) { throw new IllegalStateException(ex.toString()); } finally { //释放连接 postMethod.releaseConnection(); } System.out.println(strResponse); } } |
上面的例子,比较简单,一般是很容易看懂的,HttpClient最常见的用法是get和post方面,见下面这篇文章:HttpClient基本用法(二)
------====== 本站公告 ======------
金丝燕网,一个严谨的网站!