httpclient 操作

本文介绍如何使用HTTPClient发送JSON数据和普通数据的方法,包括设置请求头、构造请求体等关键步骤,并提供了一个测试示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

HttpClient

传json数据

public static String doPost1(String url, String json, String charset) {
		CloseableHttpClient httpClient = null;
		HttpPost httpPost = null;
		String result = null;
		try {
			httpClient = HttpClients.createDefault();
			httpPost = new HttpPost(url);
			httpPost.setHeader("Content-Type", "application/json");
			StringEntity stringEntity = new StringEntity(json, "UTF-8");// 解决中文乱码问题
			stringEntity.setContentEncoding("UTF-8");
			stringEntity.setContentType("application/json");
			httpPost.setEntity(stringEntity);
			HttpResponse response = httpClient.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, charset);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

传一般数据 

public static String doGet(String url, Map<String, String> map, String charset) {
		CloseableHttpClient httpClient = null;
		HttpGet httpPost = null;
		String result = null;
		try {
			httpClient = HttpClients.createDefault();
			httpPost = new HttpGet(url);
			// 设置参数
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			Iterator iterator = map.entrySet().iterator();
			while (iterator.hasNext()) {
				Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
				list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
			}
			if (list.size() > 0) {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
				((HttpResponse) httpPost).setEntity(entity);
			}
			HttpResponse response = httpClient.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, charset);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

 

package com.xxx.controller.tools;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpRequestRetryHandler;
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.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

public class HttpSend {

	private static CloseableHttpClient httpclient = null;

	static final int maxTotal = 500;// 总最大连接数
	static final int defaultMaxPerRoute = 100;// 每条线路最大连接数 ,本系统核心线程数,
												// 这样永远不会超过最大连接
	public static CloseableHttpClient getHttpClient() {
		if (null == httpclient) {
			synchronized (HttpSend.class) {
				if (null == httpclient) {
					httpclient = getNewHttpClient();
					System.out.println("初始化连接完成....");
				}
			}
		}
		return httpclient;
	}

	private static CloseableHttpClient getNewHttpClient() {
		// 设置连接池
		ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
		LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
		Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
				.register("http", plainsf).register("https", sslsf).build();
		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
		// 配置最大连接数
		cm.setMaxTotal(maxTotal);
		// 配置每条线路的最大连接数
		cm.setDefaultMaxPerRoute(defaultMaxPerRoute);

		// 请求重试处理
		HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
			@Override
			public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
				if (executionCount >= 2) {// 如果已经重试了2次,就放弃
					return false;
				}
				if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
					return true;
				}
				if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
					return false;
				}
				if (exception instanceof InterruptedIOException) {// 超时
					return false;
				}
				if (exception instanceof UnknownHostException) {// 目标服务器不可达
					return false;
				}
				if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
					return false;
				}
				if (exception instanceof SSLException) {// SSL握手异常
					return false;
				}

				HttpClientContext clientContext = HttpClientContext.adapt(context);
				HttpRequest request = clientContext.getRequest();

				if (!(request instanceof HttpEntityEnclosingRequest)) {
					return true;
				}
				return false;
			}

		};

		CloseableHttpClient newHttpclient = null;

		newHttpclient = HttpClients.custom().setConnectionManager(cm)
				// .setDefaultRequestConfig(requestConfig)
				.setRetryHandler(httpRequestRetryHandler).build();

		return newHttpclient;
	}

	/**
	 * post请求封装 方法postUrl的详细说明 <br>
	 * 编写者:zhangjj 创建时间:2018年3月9日 下午5:36:26
	 * </pre>
	 * 
	 * @param 参数类型
	 *            参数名 说明
	 * @return String 说明
	 * @throws 异常类型
	 *             说明
	 */
	public static String postUrl(String url, Map<String, Object> params) {
		String result = null;
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpSend.getHttpClient();
		// 创建httppost
		HttpPost httppost = new HttpPost(url);
		// 创建参数队列
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		// formparams.add(new BasicNameValuePair("username", "admin"));
		// formparams.add(new BasicNameValuePair("password", "123456"));
		Iterator<Map.Entry<String, Object>> params_set = params.entrySet().iterator();
		while (params_set.hasNext()) {
			Entry<String, Object> next = params_set.next();
			formparams.add(new BasicNameValuePair(next.getKey(), (String) next.getValue()));
		}
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
			System.out.println("executing request " + httppost.getURI());
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					result = EntityUtils.toString(entity, "UTF-8");
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			//连接交给池管理了,这里无需再手动关闭;
//			try {
//				httpclient.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
		}
		return result;
	}

	public String getUrl(String url) {
		String result = null;
		// CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpClient httpclient = HttpSend.getHttpClient();
		try {
			// 创建httpget.
			HttpGet httpget = new HttpGet(url);
			System.out.println("executing request " + httpget.getURI());
			// 执行get请求.
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				// 获取响应实体
				HttpEntity entity = response.getEntity();
				System.out.println("--------------------------------------");
				// 打印响应状态
				System.out.println(response.getStatusLine());
				if (entity != null) {
					// 打印响应内容长度
					System.out.println("Response content length: " + entity.getContentLength());
					// 打印响应内容
					result = EntityUtils.toString(entity, "UTF-8");
				}
				System.out.println("------------------------------------");
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			//连接交给池管理了,这里无需再手动关闭;
//			try {
//				httpclient.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
		}
		return result;
	}

}

 

桶过httpclient的post方法发送json参数进行接口测试。借鉴知乎上“云层”的提供的方法。

作者:云层
链接:https://www.zhihu.com/question/30878548/answer/121149629
来源:知乎

把要发送的json作为字符串传入body即可

复制代码

 1 public static String sendHttpPost(String url, String body) throws Exception {
 2 CloseableHttpClient httpClient = HttpClients.createDefault();
 3 HttpPost httpPost = new HttpPost(url);
 4 httpPost.addHeader("Content-Type", "application/json");
 5 httpPost.setEntity(new StringEntity(body));
 6 
 7 CloseableHttpResponse response = httpClient.execute(httpPost);
 8 System.out.println(response.getStatusLine().getStatusCode() + "\n");
 9 HttpEntity entity = response.getEntity();
10 String responseContent = EntityUtils.toString(entity, "UTF-8"); 
11 System.out.println(responseContent);
12 
13 response.close();
14 httpClient.close();
15 return responseContent;
16 }

复制代码

 

我的测试代码示例:

复制代码

 1     public static void main(String[] args) {
 2         //测试公司的API接口,将json当做一个字符串传入httppost的请求体
 3         String result = null;
 4         HttpClient client = HttpClients.createDefault();
 5         URIBuilder builder = new URIBuilder();
 6         URI uri = null;
 7         try {
 8             uri = builder.setScheme("http")
 9                       .setHost("xxx.xxx.xxx.xxx:xxxx")
10                       .setPath("/api/authorize/login")
11                       .build();
12             
13             HttpPost post = new HttpPost(uri);
14             //设置请求头
15             post.setHeader("Content-Type", "application/json");
16             String body = "{\"Key\": \"\",\"Secret\": \"\"}";
17             //设置请求体
18             post.setEntity(new StringEntity(body));
19             //获取返回信息
20             HttpResponse response = client.execute(post);
21             result = response.toString();
22         } catch (Exception e) {
23             System.out.println("接口请求失败"+e.getStackTrace());
24         }
25         System.out.println(result);
26     }

复制代码

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值