HttpURLConnection 接收网络数据出现乱码问题

2020-01-27 12:39:38   作者:MangoCool   来源:MangoCool

1、设置接收的编码 

2、接收内容须要解压缩 

代码如下:

/**
 *
 * @param URL 接口服务地址
 * @param sendText 发送内容
 * @param extHeadInfo 头信息
 * @param encoding 内容编码
 * @return
 * @throws Exception
 */
public static String doHttpsPost(String URL, String sendText, Map<String, String> extHeadInfo, String encoding) 
	throws Exception {
	log.info("Enter into doHttp(s)Post...");
	HttpsURLConnection conn = null;
	GZIPInputStream gZipS = null;
	String responseContent = "";
	int statusCode = 999;
	try {

		if (StringUtils.isEmpty(sendText)) {
			log.info("send data is null!");
			responseContent = "send data is null!";
		}

		log.info("URL: " + URL);
		URL url = new URL(URL);
		conn = (HttpsURLConnection)url.openConnection();
		SSLSocketFactory ssf = trustAllHosts();
//            HostnameVerifier oldHostnameVerifier = conn.getHostnameVerifier();
		conn.setSSLSocketFactory(ssf);
		conn.setHostnameVerifier(DO_NOT_VERIFY);
		conn.setConnectTimeout(CONN_TIME_OUT_VAL);
		conn.setReadTimeout(READ_TIME_OUT_VAL);
		conn.setRequestMethod("POST");
		conn.setUseCaches(false);
		conn.setDoInput(true);
		conn.setDoOutput(true);

		if(extHeadInfo != null && extHeadInfo.size() > 0){
			log.info("start set POST request header...");
			for(String key : extHeadInfo.keySet()){
				conn.setRequestProperty(key, extHeadInfo.get(key));
				log.info(key+ " : "+ extHeadInfo.get(key));
			}
		}

		conn.connect();
		log.info("connect to the network...");

		OutputStream os = conn.getOutputStream();
		OutputStreamWriter osw = new OutputStreamWriter(os, encoding);
		osw.write(sendText);
		osw.flush();
		osw.close();
		os.close();

		int responseCode = conn.getResponseCode();
		if(responseCode == HttpsURLConnection.HTTP_OK) {

			InputStream is = conn.getInputStream();
			gZipS = new GZIPInputStream(is);
			byte[] buffer = new byte[521];
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			for (int len; (len = gZipS.read(buffer)) > 0;) {
				baos.write(buffer, 0, len);
			}
			responseContent = new String(baos.toByteArray(), encoding);
			baos.flush();
			baos.close();
			is.close();
		} else {
			log.error("request fail! responseCode: {}", responseCode);
		}
		statusCode = responseCode;
	} catch (Exception e) {
		statusCode = 9999;
		responseContent = e.getMessage();
		log.error("HttpUtil doHttp(s)Post exception! cause: {}", responseContent);

	} finally {
		if(conn != null) {
			conn.disconnect();
		}

		if(gZipS!=null)
		{
			try {
				gZipS.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		System.out.println(responseContent);
		net.sf.json.JSONObject jsonObj = new net.sf.json.JSONObject();
		jsonObj.put("statusCode", statusCode);
		jsonObj.put("comments", statusCode==12999? "服务响应异常,请稍后重试!": responseContent);
		return jsonObj.toString();
	}
}

其中encoding=utf-8。

参考文章:

https://www.cnblogs.com/zjiacun/p/7736486.html


标签: HttpURLConnection java 乱码

分享:

上一篇Maven项目打包,将依赖包一起打入包中

下一篇给包含多个特殊字符的字符串做特殊字符转义的简单方法

关于我

一个喜欢唱歌,热衷旅行,爱好电子产品的码农。没事,跟三五好友吼上几嗓子,约上几个背着行囊去露营或者宅在家里抱着孩子敲代码。

座右铭:当你的才华还撑不起你的野心的时候,你就应该静下心来学习,永不止步!

            人生之旅历途甚长,所争决不在一年半月,万不可因此着急失望,招精神之萎葸。


Copyright 2015- 芒果酷(mangocool.com) All rights reserved. 湘ICP备14019394号

免责声明:本网站部分文章转载其他媒体,意在为公众提供免费服务。如有信息侵犯了您的权益,可与本网站联系,本网站将尽快予以撤除。