HttpClient使用示例(post、json、设置代理)

       JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是,JDK 库本身提供的功能还不够丰富。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本。
这里实现了几种常见的请求方式,包括请求、响应超时的设置;

所需jar包:httpclient-4.5.7.jar(其他版本的也可以,最好使用4.0以上的版本,因为不同版本的实现方式有部分差别);

官网下载地址:http://hc.apache.org/downloads.cgi

我的资源库下载地址:httpclient-4.5.7.jar

1.普通post请求;

2.json格式参数的请求;

3.设置代理的请求;

package com.common.utils.http;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
 * httpClient请求
 * @author zhaoheng
 * @date   2019-03-07
 */
public class HttpReq {
	
	/**
	 * POST请求
	 * @param url				请求地址
	 * @param socketTimeout		响应超时时间,根据业务而定,单位毫秒;
	 * 							如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用
	 * @param param		请求参数map集合
	 * @return
	 */
	 public static String doPost(String url, int socketTimeout, Map<String, String> param) {
	        // 创建Httpclient对象
	        CloseableHttpClient httpClient = HttpClients.createDefault();
	        CloseableHttpResponse response = null;
	        String resultString = "";
	        try {
	            // 创建Http Post请求
	            HttpPost httpPost = new HttpPost(url);
	            
	            // 设置请求超时
	            RequestConfig requestConfig = RequestConfig.custom()  
	                    .setConnectTimeout(5000)						// 设置连接超时时间,单位毫秒。
	                    .setConnectionRequestTimeout(1000)  			// 从连接池获取到连接的超时,单位毫秒。
	                    .setSocketTimeout(socketTimeout).build();    	// 请求获取数据的超时时间,单位毫秒; 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
	            httpPost.setConfig(requestConfig);
	            
	            // 创建参数列表
	            if (param != null) {
	                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
	                for (String key : param.keySet()) {
	                    paramList.add(new BasicNameValuePair(key, param.get(key)));
	                }
	                // 模拟表单
	                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
	                httpPost.setEntity(entity);
	            }
	            // 执行http请求
	            response = httpClient.execute(httpPost);
	            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
	        } catch (Exception e) {
	            e.printStackTrace();
	            if (e instanceof SocketTimeoutException) {
					System.out.println("响应超时!!!");
				}
	        } finally {
	        	// 释放资源
	            try {
	            	if (null != httpClient) {
	            		httpClient.close();
					}
	            	if (null != response) {
	            		response.close();
					}
	            } catch (IOException e) {
	                
	                e.printStackTrace();
	            }
	        }

	        return resultString;
	    }
	 
	 /**
	  * POST请求(带json参数)
	  * @param url					请求地址
	  * @param socketTimeout		响应超时时间,根据业务而定,单位毫秒;
	  * 							如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用
	  * @param jsonParam	json参数
	  * @return
	  */
	 public static String doPostJson(String url, int socketTimeout, String jsonParam) {
	        // 创建Httpclient对象
	        CloseableHttpClient httpClient = HttpClients.createDefault();
	        CloseableHttpResponse response = null;
	        String resultString = "";
	        try {
	            // 创建Http Post请求
	            HttpPost httpPost = new HttpPost(url);
	            
	            // 设置请求超时
	            RequestConfig requestConfig = RequestConfig.custom()  
	                    .setConnectTimeout(5000)						// 设置连接超时时间,单位毫秒。
	                    .setConnectionRequestTimeout(1000)  			// 从连接池获取到连接的超时,单位毫秒。
	                    .setSocketTimeout(socketTimeout).build();    	// 请求获取数据的超时时间,单位毫秒; 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
	            httpPost.setConfig(requestConfig);
	            
	            // 创建请求内容
	            StringEntity entity = new StringEntity(jsonParam, ContentType.APPLICATION_JSON);
	            httpPost.setEntity(entity);
	            // 执行http请求
	            response = httpClient.execute(httpPost);
	          
	            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
	        } catch (Exception e) {
	            e.printStackTrace();
	            if (e instanceof SocketTimeoutException) {
					System.out.println("响应超时!!!");
				}
	        } finally {
	        	// 释放资源
	            try {
	            	if (null != httpClient) {
	            		httpClient.close();
					}
	            	if (null != response) {
	            		response.close();
					}
	            } catch (IOException e) {
	                
	                e.printStackTrace();
	            }
	        }

	        return resultString;
	    }

	 /**
	  * 需要设置代理POST请求(带json参数)
	  * @param proxyIp	代理IP
	  * @param port		端口号
	  * @param tcp		协议(例:http、https)
	  * @param url		请求地址
	  * @param socketTimeout		响应超时时间,根据业务而定,单位毫秒;
	  * 							如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用
	  * @param jsonParam	json参数
	  * @return
	  */
	 public static String doProxyPostJson(String proxyIp,int port,String tcp, String url,int socketTimeout, String jsonParam) {
		 	//设置代理IP、端口、协议
	        HttpHost proxy = new HttpHost(proxyIp, port, tcp);

	        //把代理设置到请求配置
	        RequestConfig defaultRequestConfig = RequestConfig.custom().setProxy(proxy).build();

	        //实例化CloseableHttpClient对象
	        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
	        
	        CloseableHttpResponse response = null;
	        String resultString = "";
	        try {
	            // 创建Http Post请求
	            HttpPost httpPost = new HttpPost(url);
	            
	            // 设置请求超时
	            RequestConfig requestConfig = RequestConfig.custom()  
	                    .setConnectTimeout(5000)						// 设置连接超时时间,单位毫秒。
	                    .setConnectionRequestTimeout(1000)  			// 从连接池获取到连接的超时,单位毫秒。
	                    .setSocketTimeout(socketTimeout).build();    	// 请求获取数据的超时时间,单位毫秒; 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
	            httpPost.setConfig(requestConfig);
	            
	            // 创建请求内容
	            StringEntity entity = new StringEntity(jsonParam, ContentType.APPLICATION_JSON);
	            httpPost.setEntity(entity);
	            // 执行http请求
	            response = httpClient.execute(httpPost);
	          
	            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
	        } catch (Exception e) {
	            e.printStackTrace();
	            if (e instanceof SocketTimeoutException) {
					System.out.println("响应超时!!!");
				}
	        } finally {
	        	// 释放资源
	            try {
	            	if (null != httpClient) {
	            		httpClient.close();
					}
	            	if (null != response) {
	            		response.close();
					}
	            } catch (IOException e) {
	                
	                e.printStackTrace();
	            }
	        }

	        return resultString;
	    }
	 
	 	/**
	 	 * 需要设置代理的 POST请求
	 	 * @param proxyIp	代理IP
	 	 * @param port		端口号
	 	 * @param tcp		协议(例:http、https)
	 	 * @param url		请求地址
	 	 * @param socketTimeout		响应超时时间,根据业务而定,单位毫秒;
	 	 * 							如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用
	 	 * @param param		请求参数map集合
	 	 * @return
	 	 */
		 public static String doProxyPost(String proxyIp,int port,String tcp, String url, int socketTimeout, Map<String, String> param) {
			 
			 	//设置代理IP、端口、协议
		        HttpHost proxy = new HttpHost(proxyIp, port, tcp);

		        //把代理设置到请求配置
		        RequestConfig defaultRequestConfig = RequestConfig.custom().setProxy(proxy).build();

		        //实例化CloseableHttpClient对象
		        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
		        CloseableHttpResponse response = null;
		        String resultString = "";
		        try {
		            // 创建Http Post请求
		            HttpPost httpPost = new HttpPost(url);
		            
		            // 设置请求超时
		            RequestConfig requestConfig = RequestConfig.custom()
		                    .setConnectTimeout(5000)						// 设置连接超时时间,单位毫秒。
		                    .setConnectionRequestTimeout(1000)				// 从连接池获取到连接的超时,单位毫秒。
		                    .setSocketTimeout(socketTimeout).build();    	// 请求获取数据的超时时间,单位毫秒; 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
		            httpPost.setConfig(requestConfig);
		            
		            // 创建参数列表
		            if (param != null) {
		                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
		                for (String key : param.keySet()) {
		                    paramList.add(new BasicNameValuePair(key, param.get(key)));
		                }
		                // 模拟表单
		                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
		                httpPost.setEntity(entity);
		            }
		            // 执行http请求
		            response = httpClient.execute(httpPost);
		            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		        } catch (Exception e) {
		            e.printStackTrace();
		            if (e instanceof SocketTimeoutException) {
						System.out.println("响应超时!!!");
					}
		        } finally {
		        	// 释放资源
		            try {
		            	if (null != httpClient) {
		            		httpClient.close();
						}
		            	if (null != response) {
		            		response.close();
						}
		            } catch (IOException e) {
		                
		                e.printStackTrace();
		            }
		        }

		        return resultString;
		    }
	 
	 /**
	  * 测试方法
	  * @param args
	  */
	 public static void main(String[] args) {
		 
		 // 测试post请求
		 String url = "http://127.0.0.1:8080/download/TestCon/test01";
		 Map<String, String> param = new HashMap<String, String>();
			param.put("name", "welcome");
		 String result = HttpReq.doPost(url,3000, param);
		 System.out.println("result:"+result);
		 
		 // 测试json参数请求
		 String url2 = "http://127.0.0.1:8080/download/TestCon/test02";
		 String jsonParam = "{\"fileName\":\"httpClient.jar\",\"fileSize\":\"1024\"}";
		 String result2 = HttpReq.doPostJson(url2,5000, jsonParam);
		 System.out.println("result2:"+result2);

		 // 代理请求测试
		 String url3 = "https://www.baidu.com";
		 Map<String, String> param3 = new HashMap<String, String>();
		 String result3 = HttpReq.doProxyPost("代理ip", 8080, "http", url3,5000, param3);
		 System.out.println(result3);
	 }
}

 

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您也可以使用Apache HttpClient库来模拟发送POST请求,并将JSON数据作为请求体发送。以下是一个示例代码: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import java.io.BufferedReader; import java.io.InputStreamReader; public class PostJsonRequest { public static void main(String[] args) { try { // 设置请求URL和JSON数据 String url = "http://example.com/api"; String json = "{\"name\": \"John\", \"age\": 30}"; // 创建HttpClient和HttpPost对象 HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); // 将JSON数据作为请求体发送 StringEntity entity = new StringEntity(json); post.setEntity(entity); post.setHeader("Content-type", "application/json"); post.setHeader("Accept", "application/json"); // 发送请求并获取响应 HttpResponse response = client.execute(post); // 打印响应内容 BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { System.out.println(line); } } catch (Exception e) { e.printStackTrace(); } } } ``` 在上述示例中,我们使用了Apache HttpClient库来创建HttpClient和HttpPost对象,并将JSON数据作为请求体发送。注意:在实际使用时,您需要将URL和JSON数据替换为实际的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值