相对于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)//设置服务器请求超时
.socketTimeout(1000)//设置服务器相应超时
.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);
}
}