一:使用步骤:
1. 创建HttpClient对象。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接
HttpClient:是一个接口
首先需要先创建一个DefaultHttpClient的实例
HttpClient httpClient=new DefaultHttpClient();
发送GET请求:
先创建一个HttpGet对象,传入目标的网络地址,然后调用HttpClient的execute()方法即可:
HttpGet HttpGet=new HttpGet(“http://www.baidu.com”);
httpClient.execute(httpGet);
发送POST请求:
1.创建一个HttpPost对象,传入目标的网络地址:
HttpPost httpPost=new HttpPost(“http://www.baidu.com”);
2.通过一个NameValuePair集合来存放待提交的参数,并将这个参数集合传入到一个UrlEncodedFormEntity中,然后调用HttpPost的setEntity()方法将构建好的UrlEncodedFormEntity传入:
List<NameValuePair>params=newArrayList<NameValuePair>();
Params.add(new BasicNameValuePair(“username”,”admin”));
Params.add(new BasicNameValuePair(“password”,”123456”));
UrlEncodedFormEntity entity=newUrlEncodedFormEntity(params,”utf-8”);
httpPost.setEntity(entity);
调用HttpClient的execute()方法,并将HttpPost对象传入即可:
HttpClient.execute(HttpPost);
3.执行execute()方法之后会返回一个HttpResponse对象,服务器所返回的所有信息就保护在HttpResponse里面.
先取出服务器返回的状态码,如果等于200就说明请求和响应都成功了:
If(httpResponse.getStatusLine().getStatusCode()==200){
//请求和响应都成功了
HttpEntityentity=HttpResponse.getEntity();//调用getEntity()方法获取到一个HttpEntity实例
String response=EntityUtils.toString(entity,”utf-8”);//用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了
}
二:代码例子:简单demo例子:
package ks.httpclient;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* @author 47475
*
* @category 简单Get请求百度
*/
public class HttpClient1 {
public static void main(String args[]) throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
String url = "http://www.baidu.com";
HttpGet httpGet = new HttpGet(url);
System.out.println("executing request " + httpGet.getURI());
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity, "utf-8") : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
};
String responseBody = httpclient.execute(httpGet, responseHandler);
System.out.println("-------------------------------------------");
System.out.println(responseBody);
System.out.println("-------------------------------------------");
} finally {
httpclient.close();
}
}
}
工具类:HttpClientUtil.java
package ks.httpclient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
* @author xin.ding
*
*/
public class HttpClientUtils {
private static PoolingHttpClientConnectionManager connectionManager = null;
private static HttpClientBuilder httpBuilder = null;
/** 请求状态参数 */
private static RequestConfig requestConfig = null;
/** 客户端总并行链接最大数 */
private static int MAXCONNECTION = 10;
/** 每个主机的最大并行链接数 */
private static int DEFAULTMAXCONNECTION = 5;
private static String IP = "cnivi.com.cn";
private static int PORT = 80;
static {
requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
.setConnectionRequestTimeout(5000).build();
HttpHost target = new HttpHost(IP, PORT);
connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(MAXCONNECTION);
connectionManager.setDefaultMaxPerRoute(DEFAULTMAXCONNECTION);
connectionManager.setMaxPerRoute(new HttpRoute(target), 20);
httpBuilder = HttpClients.custom();
httpBuilder.setConnectionManager(connectionManager);
}
/** 获取HttpClient对象 */
public static CloseableHttpClient getConnection() {
CloseableHttpClient httpClient = httpBuilder.build();
return httpClient;
}
/**
* 获取请求方式对象,比如HttpGet对象HttpPost对象
*
* @param map 传递参数
* @param url 请求地址
* @param method 请求方式
*/
public static HttpUriRequest getRequestMethod(Map<String, String> map, String url, String method) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (map != null) {
Set<Map.Entry<String, String>> entrySet = map.entrySet();
for (Map.Entry<String, String> e : entrySet) {
String name = e.getKey();
String value = e.getValue();
NameValuePair pair = new BasicNameValuePair(name, value);
params.add(pair);
}
}
HttpUriRequest reqMethod = null;
if ("post".equals(method)) {
reqMethod = RequestBuilder.post().setUri(url)
.addParameters(params.toArray(new BasicNameValuePair[params.size()])).setConfig(requestConfig)
.build();
} else if ("get".equals(method)) {
reqMethod = RequestBuilder.get().setUri(url)
.addParameters(params.toArray(new BasicNameValuePair[params.size()])).setConfig(requestConfig)
.build();
}
return reqMethod;
}
public static void main(String args[]) throws IOException {
// Map<String, String> map = new HashMap<String, String>();
// map.put("account", "");
// map.put("password", "");
HttpClient client = getConnection();
HttpUriRequest get = getRequestMethod(null, "http://www.baidu.com", "get");
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
String message = EntityUtils.toString(entity, "utf-8");
System.out.println(message);
} else {
System.out.println("请求失败");
}
}
}