HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
1.引入jar包
http://hc.apache.org/downloads.cgi
2.需要一个HttpClientUtils工具类
package cn.happy.util; 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; import java.io.IOException; import java.util.*; 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 { //设置http的状态参数 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); } public static CloseableHttpClient getConnection() { CloseableHttpClient httpClient = httpBuilder.build(); return httpClient; } public static HttpUriRequest getRequestMethod(Map<String, String> map, String url, String method) { List<NameValuePair> params = new ArrayList<NameValuePair>(); 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 post = getRequestMethod(map, "http://cnivi.com.cn/login", "post"); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); String message = EntityUtils.toString(entity, "utf-8"); System.out.println(message); } else { System.out.println("请求失败"); } } }
3.发送Get请求
@Test public void tGet() throws IOException { //创建CloseableHttpClient对象,并为HttpClients赋默认值 CloseableHttpClient httpClient= HttpClients.createDefault(); //创建get请求http://www.baidu.com/ http://localhost:8080/isSelectUserto HttpGet httpGet=new HttpGet("https://home.cnblogs.com/u/java-263/"); System.out.println("httpget的请求路径:"+httpGet.getURI()); //得到响应结果 CloseableHttpResponse httpResponse=httpClient.execute(httpGet); //为HttpEntity创建实体 HttpEntity httpEntity=httpResponse.getEntity(); System.out.println("============================"); //打印响应状态 System.out.println( httpResponse.getStatusLine()); if (httpEntity!=null){ //打印响应内容长度 System.out.println("entity length:"+httpEntity.getContentLength()); //打印响应内容 System.out.println("entity:"+EntityUtils.toString(httpEntity,"UTF-8")); } httpResponse.close(); httpClient.close(); }
4.发送Post请求
@Test public void tPost() throws IOException { CloseableHttpClient httpClient=HttpClients.createDefault(); /*=============================POST请求多出的部分内容=================================================*/ HttpPost httpPost=new HttpPost("http://localhost:8080/isSelectUserto"); //创建参数队列 List<NameValuePair> list=new ArrayList<NameValuePair>(); list.add(new BasicNameValuePair("type","house")); UrlEncodedFormEntity encodedFormEntity; encodedFormEntity=new UrlEncodedFormEntity(list,"UTF-8"); /*====================================POST请求多出的部分内容==========================================*/ httpPost.setEntity(encodedFormEntity); System.out.println("URL:"+httpPost.getURI()); /* System.out.println("entity length:"+ httpPost.getEntity().getContentLength());*/ CloseableHttpResponse httpResponse=httpClient.execute(httpPost); HttpEntity httpEntity=httpResponse.getEntity(); if (httpEntity!=null){ System.out.println("entity length:"+httpEntity.getContentLength()); System.out.println("Response content: " + EntityUtils.toString(httpEntity, "UTF-8")); } httpResponse.close(); httpClient.close(); }
更多了解参考:https://blog.csdn.net/zhuwukai/article/details/78644484