HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的Java 应用程序需要直接通过
HTTP协议来访问网络资源。
虽然在 JDK 的 java net包中已经提供了访问 HTTP协议的基本功能,但是对于大部分应用程序来说,JDK 库本
身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common下的子项目,用来提供高效的、最新的、功
能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持HTTP 协议最新的版本和建议。HttpClient 已经应用在很
多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和HTMLUnit 都使用了 HttpClient。现在
HttpClient最新版本为 HttpClient 4.3 (GA)(2013-9-23)。
开发 7 步骤 :
1、导入jar包
4、执行请求
5、获取响应
6、关闭响应
7、关闭httpclient
package quickStart;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class QuickStar {
public static void main(String[] args) throws IOException{
//==============httppGet开始=================
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://www.baidu.com");
httpget.addHeader(new BasicHeader("", ""));
httpget.addHeader("", "");
CloseableHttpResponse httpReponse = httpClient.execute(httpget);
try{
//获取状态行
System.out.println(httpReponse.getStatusLine());
HttpEntity entity = httpReponse.getEntity();
//返回内容
System.out.println(EntityUtils.toString(entity));
}finally{
httpReponse.close();
}
//httpClient.close();
//===============httppPst结束=================
//===============httppPst请求开始==============
HttpPost httpPost = new HttpPost("http://targethost/login");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", "myusername"));
nvps.add(new BasicNameValuePair("password", "mypassword"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse httppHttpResponse2 = httpClient.execute(httpPost);
try{
System.out.println(httppHttpResponse2.getStatusLine());
System.out.println(EntityUtils.toString(httppHttpResponse2.getEntity()));
}finally{
httppHttpResponse2.close();
}
httpClient.close();
}
//===============httppPst请求结束==============
}
另一种不考虑性能的情况下的请求:
package cn.cun.com.htpclient;
import java.io.IOException;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
public class QuickStart2 {
public static void main(String[] args) throws IOException {
Content content = Request.Get("http://www.baidu.com").execute().returnContent();
System.out.println(content);
content = Request.Post("http://targeHost/homePage/login").bodyForm(Form.form().add("username", "ss").add("password", "ss").build()).execute().returnContent();
System.out.println(content);
}
}