HttpClient POST 解决中文乱码

  • Post author:
  • Post category:其他


HttpClient 默认情况下编码格式是ISO,需要设置postMethod方法的编码为utf-8

网上看的方法很多,有种重写postMethod方法,测试可以成功。

也可以用下方法:

public class HttpRequestUtil {


	private final static Logger log = LoggerFactory.getLogger(HttpRequestUtil.class);
	private static final int TIMEOUT = 20 * 60 * 1000;
	private static CloseableHttpClient sslHttpClient;
	private static CloseableHttpClient httpClient;
	static{
		SSLContextBuilder builder = new SSLContextBuilder();
		try {
			//httpclient初始化
			httpClient = HttpClients.createDefault();
			//httpsClient初始化  全部信任 不做身份鉴定
			builder.loadTrustMaterial(null, new TrustStrategy() {
				@Override
				public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
					return true;
				}
			});
			SSLConnectionSocketFactory  sslsf = new SSLConnectionSocketFactory(builder.build(), 
					NoopHostnameVerifier.INSTANCE);
			Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
					.register("http", new PlainConnectionSocketFactory())
					.register("https", sslsf)
					.build();
			PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
			cm.setMaxTotal(10);//max connection
			sslHttpClient = HttpClients.custom()
					.setSSLSocketFactory(sslsf)
					.setConnectionManager(cm)
					.setConnectionManagerShared(true)
					.build();
		} catch (Exception e) {
			log.error("初始化restTemplate异常",e);
		} 
	}

	public static String sendRequest(String method, String urlString, String param){
		if(method == null || urlString == null ) return null;
		CloseableHttpResponse response = null;
		CloseableHttpClient hc = null;
		try {
			//根据不同协议选择是httpsClient 或 httpclient
			if(urlString.startsWith("https")){
				hc = sslHttpClient;
			}else {
				hc = httpClient;
			}
			if("get".equalsIgnoreCase(method)){
				HttpGet hg=new HttpGet(urlString);
				response = hc.execute(hg);
			}else{
				HttpPost hp=new HttpPost(urlString);
				hp.setEntity(new StringEntity(param, "utf-8"));
				hp.addHeader("Content-Type", "application/json;charset=utf-8");
				response = hc.execute(hp);
			}
			int statusCode = response.getStatusLine().getStatusCode();
			if(statusCode == 200){
				return EntityUtils.toString(response.getEntity(), "utf-8");
			}else{
				log.error("接口调用返回码:",statusCode);
				log.error(EntityUtils.toString(response.getEntity(), "utf-8"));
			}
		} catch (Exception e) {
			log.error("请求发送异常:"+urlString);
			log.error("请求参数::"+param);
			log.error("异常堆栈:",e);
		}finally{
			try {
				if(response != null) response.close();
			} catch (Exception e2) {
			}

		}
		return null;
	}

	public static String  sendFile(String urlString,HttpEntity he){
		CloseableHttpResponse response = null;
		CloseableHttpClient hc = null;
		try {
			//根据不同协议选择是httpsClient 或 httpclient
			if(urlString.startsWith("https")){
				hc = sslHttpClient;
			}else {
				hc = httpClient;
			}
			HttpPost hp=new HttpPost(urlString);
			hp.setEntity(he);
			response = hc.execute(hp);
			int statusCode = response.getStatusLine().getStatusCode();
			if(statusCode == 200){
				return EntityUtils.toString(response.getEntity(), "utf-8");
			}else{
				log.error("接口调用返回码:",statusCode);
				log.error(EntityUtils.toString(response.getEntity(), "utf-8"));
			}
		} catch (Exception e) {
			log.error("请求发送异常:",urlString);
			log.error("异常堆栈:",e);
		}finally{
			try {
				if(response != null) response.close();
			} catch (Exception e2) {
			}

		}
		return null;
	}
	/**
	 * @param param 黑名单
	 * @return
	 */
	public String verificationForString(String param){
		List<String> list=new ArrayList<String>();
		list.add("!");
		list.add("@");
		list.add("#");
		list.add("$");
		list.add("%");
		list.add("^");
		list.add("&");
		list.add("*");
		list.add("(");
		list.add(")");
		list.add("-");
		list.add("=");
		list.add("+");
		list.add("/");
		list.add("\\");
		list.add("<");
		list.add(">");
		list.add("?");
		for (int i = 0; i < list.size(); i++) {
			if (param.contains(list.get(i))) {
				return "";
			}
		}
		return param;
	}

	public static String jsonToPost(String url, String param) {
		HttpPost httpPost = null;
		String result = null;
		CloseableHttpClient hc = null;
		try {
			if(url.startsWith("https")){
				hc = sslHttpClient;
			}else {
				hc = httpClient;
			}
			//            httpClient = HttpClients.custom().build();
			RequestConfig requestConfig = RequestConfig.custom()
					.setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).build();
			httpPost = new HttpPost(url);
			httpPost.setConfig(requestConfig);
			if (param != null) {
				StringEntity se = new StringEntity(param, "utf-8");
				httpPost.setEntity(se); // post方法中,加入json数据
				httpPost.setHeader("Content-Type", "application/json");
			}
			HttpResponse response = hc.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, "utf-8");
				}
			}
		} catch (Exception ex) {
		}
		return result;
	}

	public static String postFormData(String urlString,Map<String, String> bodyMap, byte[] bs, String filename) {
		CloseableHttpClient hc = null;
		HttpPost httpPost = null;
		String result = "";
		try {
			if(urlString.startsWith("https")){
				hc = sslHttpClient;
			}else {
				hc = httpClient;
			}
			//            httpClient = HttpClients.custom().build();
			RequestConfig requestConfig = RequestConfig.custom()
					.setSocketTimeout(100000).setConnectTimeout(100000).build();
			httpPost = new HttpPost(urlString);
			httpPost.setConfig(requestConfig);
			//创建 MultipartEntityBuilder,以此来构建我们的参数
			MultipartEntityBuilder EntityBuilder = MultipartEntityBuilder.create();
			//设置字符编码,防止乱码
			ContentType contentType=ContentType.create("text/plain", Charset.forName("UTF-8"));
			//填充我们的文本内容,这里相当于input 框中的 name 与value
			for(String key : bodyMap.keySet()) {
				EntityBuilder.addPart(key, new StringBody(bodyMap.get(key),contentType));
			}
			//上传我们的文件
			if(bs != null) {
				EntityBuilder.addBinaryBody("data", bs, ContentType.DEFAULT_BINARY,filename);
			}
			//参数组装
			httpPost.setEntity(EntityBuilder.build());
			CloseableHttpResponse response = hc.execute(httpPost);
			HttpEntity httpEntity = response.getEntity();
			result = EntityUtils.toString(httpEntity, "utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	
	public static String sendRequestToken(String method,String urlString,String param,boolean type){
		if(method == null || urlString == null ) return null;
		CloseableHttpResponse response = null;
		CloseableHttpClient hc = null;
		try {
			//根据不同协议选择是httpsClient 或 httpclient
			if(urlString.startsWith("https")){
				hc = sslHttpClient;
			}else {
				hc = httpClient;
			}
			if("get".equalsIgnoreCase(method)){
				HttpGet hg=new HttpGet(urlString);
				response = hc.execute(hg);
			}else{
				HttpPost hp=new HttpPost(urlString);
				hp.setHeader("Content-Type", "application/json");
				hp.setEntity(new StringEntity(param, "utf-8"));
				response = hc.execute(hp);
			}
			int statusCode = response.getStatusLine().getStatusCode();
			if(statusCode == 200){
				return EntityUtils.toString(response.getEntity(), "utf-8");
			}else{
				log.error("接口调用返回码:",statusCode);
				log.error(EntityUtils.toString(response.getEntity(), "utf-8"));
			}
		} catch (Exception e) {
			log.error("请求发送异常:"+urlString);
			log.error("请求参数::"+param);
			log.error("异常堆栈:",e);
		}finally{
			try {
				if(response != null) response.close();
			} catch (Exception e2) {
			}
		}
		return null;
	}
}



版权声明:本文为Mrloserc原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。