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 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。
参考文章:
分享: