JAVA: httpclient 具体解释——第五章;

时间:2023-03-09 00:00:15
JAVA: httpclient 具体解释——第五章;

httpclient 具体解释——第一章;

httpclient 具体解释——第二章;

httpclient 具体解释——第三章;

httpclient 具体解释——第四章;

httpclient 具体解释——第五章;

httpclient 具体解释——第六章;

httpclient 具体解释——第七章;

相对于httpurlconnection ,httpclient更加丰富,也更加强大,当中apache有两个项目都是httpclient,一个是commonts包下的,这个是通用的,更专业的是org.apache.http.包下的,所以我一般用后者;

httpclient能够处理长连接,保存会话,重连接,以及请求过滤器,连接重用等等...

以下是測试代码(所有总结来自官方文档,以及翻译)

需要下载核心包:httpclient-4.3.4.jar ,也可在官网下载:http://hc.apache.org/downloads.cgi

//--------------------------  高速API ---------------------------------

	/**
* 高速api仅仅提供最主要的功能,仅仅用于不需要灵活扩展的场景
*/
private static void test22() throws ClientProtocolException, IOException{ String result = Request.Get("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo")
.connectTimeout(1000)//设置server请求超时
.socketTimeout(1000)//设置server对应超时
.execute()
.returnContent()
.asString(); String result2 = Request.Post("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo")
.useExpectContinue()
.version(HttpVersion.HTTP_1_1)
.bodyString("參数", ContentType.DEFAULT_TEXT)
.execute()
.returnContent()
.asString(); //提交HTML表单 ,并保存返回结果
Request.Post("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo")
.addHeader("X-Custom-header", "stuff") // 表单头
.viaProxy(new HttpHost("myproxy", 8080)) // 设置代理
.bodyForm(Form.form() //表单
.add("mobileCode", "12345")
.add("userID", "123456")
.build())
.execute()
.saveContent(new File("result.txt")); System.out.println(result);
System.out.println(result2); } /**
* 利用Executor 高速开发;
* 假设需要在指定的安全上下文中运行某些请求,我们也能够直接使用Exector,
* 这时候用户的认证信息就会被缓存起来,以便兴许的请求使用。
*/
private static void test23() throws ClientProtocolException, IOException{ Executor executor = Executor.newInstance()
.auth(new HttpHost("somehost",8080), "username", "password")//加入认证
.authPreemptive(new HttpHost("somehost", 8080)); //使用抢先认证 executor.execute(Request.Get("http://somehost/"))//运行get请求
.returnContent().asString(); executor.execute(Request.Post("http://somehost/") //运行post请求
.useExpectContinue()
.bodyString("Important stuff", ContentType.DEFAULT_TEXT))
.returnContent().asString(); } /**
*
* 高速响应处理
*
* 利用request高速发送get请求,并用ResponseHandler 回调返回结果;
*/
private static void test24() throws ClientProtocolException, IOException { Object result = Request .Get("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo")
.execute().handleResponse(new ResponseHandler<Object>() { public Object handleResponse(final HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); if(statusLine.getStatusCode()==200){ HttpEntity entity = response.getEntity();
if (entity != null) {
String str = EntityUtils.toString(entity);
return str;
}
} return null;
} }); if (result != null) {
System.out.println(">>>>>>"+result);
} }