溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

使用httpclient對(duì)json數(shù)據(jù)進(jìn)行傳遞時(shí)出現(xiàn)亂碼如何解決

發(fā)布時(shí)間:2021-01-21 14:52:37 來(lái)源:億速云 閱讀:392 作者:Leah 欄目:開發(fā)技術(shù)

今天就跟大家聊聊有關(guān)使用httpclient對(duì)json數(shù)據(jù)進(jìn)行傳遞時(shí)出現(xiàn)亂碼如何解決,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

(1)修改前:

client端

 public String sendHttpPost(String httpUrl, String data) {
 
 // 創(chuàng)建post請(qǐng)求
 HttpPost httpPost = new HttpPost(httpUrl);
 StringEntity entity;
 try {
 entity = new StringEntity(data);
 entity.setContentEncoding("UTF-8");
 entity.setContentType("application/json");
 httpPost.setEntity(entity);
 } catch (UnsupportedEncodingException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 
 return sendHttpPost(httpPost);
 }
private String sendHttpPost(HttpPost httpPost) {
 
 CloseableHttpClient httpClient = null;
 CloseableHttpResponse response = null;
 HttpEntity entity = null;
 String responseContent = null;
 
 // 創(chuàng)建默認(rèn)的httpclient實(shí)例
 httpClient = HttpClients.createDefault();
 httpPost.setConfig(requestConfig);
 httpPost.setHeader("Accept","aplication/json");
 httpPost.addHeader("Content-Type","application/json;charset=UTF-8");
 // 執(zhí)行請(qǐng)求
 try {
 logger.info("開始同步數(shù)據(jù)");
 response = httpClient.execute(httpPost);
 entity = response.getEntity();
 responseContent = EntityUtils.toString(entity, "UTF-8");
 logger.info("數(shù)據(jù)同步結(jié)果:" + responseContent);
 } catch (IOException e) {
 logger.error("同步數(shù)據(jù)出錯(cuò):" + e.toString());
 e.printStackTrace();
 } finally {
 try {
 if (response != null) {
  response.close();
 }
 if (httpClient != null) {
  httpClient.close();
 }
 
 } catch (Exception e2) {
 logger.error("流關(guān)閉出錯(cuò):" + e2.toString());
 }
 
 }
 return responseContent;
 }

(2)修改后

client端

 public String sendHttpPost(String httpUrl, String data) {
 
 // 創(chuàng)建post請(qǐng)求
 HttpPost httpPost = new HttpPost(httpUrl);
 StringEntity entity;
 entity = new StringEntity(data,"UTF-8");
 entity.setContentType("application/json");
 //entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));//用這個(gè)跟上面一行那個(gè)結(jié)果一樣,可以查看源碼
 httpPost.setEntity(entity);
 
 return sendHttpPost(httpPost);
 }
 
 private String sendHttpPost(HttpPost httpPost) {
 
 CloseableHttpClient httpClient = null;
 CloseableHttpResponse response = null;
 HttpEntity entity = null;
 String responseContent = null;
 
 // 創(chuàng)建默認(rèn)的httpclient實(shí)例
 httpClient = HttpClients.createDefault();
 httpPost.setConfig(requestConfig);
 httpPost.setHeader("Accept","aplication/json");
 
 httpPost.addHeader("Content-Type","application/json;charset=UTF-8");
 }

服務(wù)端 代碼

 //服務(wù)端 代碼 通過(guò)紅色字體的代碼接受數(shù)據(jù)
 public Map<String, Object> getRequestPostParams(HttpServletRequest request) throws BusinessException {
 try {
 //接收數(shù)據(jù)
 StringBuffer sb = new StringBuffer() ;
 InputStream is = request.getInputStream(); 
 InputStreamReader isr = new InputStreamReader(is, "utf-8"); 
 BufferedReader br = new BufferedReader(isr); 
 String s = "" ; 
 while((s=br.readLine())!=null){ 
 
 sb.append(s) ; 
 } 
 String strData = sb.toString();
 
 if (null == strData || "".equals(strData)) {
 return new HashMap<String, Object>();
 }
 Map<String, Object> params = this.parseJSON2Map(strData);
 return params;
 
 } catch(Exception e) {
 throw new BusinessException(BusinessException.ERROR_INNER, "參數(shù)轉(zhuǎn)換錯(cuò)誤!");
 }
 }

下面來(lái)解釋原因:

看到這里 發(fā)現(xiàn)了client端的不同的吧,沒(méi)錯(cuò) 只有一行代碼不一樣

entity = new StringEntity(data,"UTF-8");

就是這行代碼,因?yàn)闃?gòu)造方法的不同造成的

本來(lái)參考了這篇文章把問(wèn)題解決了,但是我發(fā)現(xiàn) 我自己的代碼明明也設(shè)置額編碼 為什么會(huì)出現(xiàn)亂碼呢,于是我就去看源代碼的實(shí)現(xiàn),差異在哪里? 下面貼上源代碼

public StringEntity(final String string, final ContentType contentType) throws UnsupportedCharsetException {
 
 super();
 Args.notNull(string, "Source string");
 Charset charset = contentType != null ? contentType.getCharset() : null;
 if (charset == null) {
  charset = HTTP.DEF_CONTENT_CHARSET;
 }
 try {
  this.content = string.getBytes(charset.name());
 } catch (final UnsupportedEncodingException ex) {
  // should never happen
  throw new UnsupportedCharsetException(charset.name());
 }
 if (contentType != null) {
  setContentType(contentType.toString());
 }
 
 }

然后就發(fā)現(xiàn),在new StringEntity的時(shí)候,就已經(jīng)將數(shù)據(jù)根據(jù)編碼進(jìn)行了處理,也就是說(shuō),如果你調(diào)用 new StringEntity(String string)此構(gòu)造方法,就會(huì)使用其默認(rèn)的編碼進(jìn)行轉(zhuǎn)碼(ISO-8859-1),無(wú)論你后面設(shè)置多少次(

entity.setContentEncoding("UTF-8");

或者

httpPost.addHeader("Content-Type","application/json;charset=UTF-8");

都不會(huì)改變字符串已經(jīng)被按轉(zhuǎn)碼變成Byte[]數(shù)組的事實(shí),當(dāng)然在請(qǐng)求中設(shè)定傳輸編碼格式還是要做的。

其實(shí)說(shuō)這么多 ,解決問(wèn)題的關(guān)鍵就一句話,在new StringEntity()的時(shí)候指定編碼就解決了,因?yàn)樵趎ew的同時(shí)已經(jīng)做了字符串的轉(zhuǎn)碼操作

之所以說(shuō)這么多,是想告訴自己,問(wèn)題解決了固然是好,但應(yīng)該知道為什么這么做,多看源碼,多問(wèn)自己為什么,僅此共勉。

補(bǔ)充:httpclient post發(fā)送json數(shù)組并解決json亂碼問(wèn)題

業(yè)務(wù):

客戶端發(fā)送json數(shù)據(jù),服務(wù)端進(jìn)行解析

client發(fā)送json格式:

{"data":[{"name":"1;,a","id_no":"222,a","cellphone":"123141a","abode_detail":"213,a","emp_add":"werew3a","app_no":"111111111111a","create_time":"11a"},{"name":"張三","id_no":"null","cellphone":"null","abode_detail":"null","emp_add":"null","app_no":"null","create_time":"null"},{"name":"1;,","id_no":"222,","cellphone":"123141","abode_detail":"213,","emp_add":"werew3","app_no":"111111111111","create_time":"11"},{"name":"1;,ab","id_no":"222,ab","cellphone":"123141ab","abode_detail":"213,ab","emp_add":"werew3ab","app_no":"111111111111ab","create_time":"11ab"}],"sendtime":"20160503"}

廢話少說(shuō),直接上主要代碼

client端

package msxf.until;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import msxf.until.model.People;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by 小省.
 */
public class Main {
 private final static org.apache.log4j.Logger logger =org.apache.log4j.Logger.getLogger(Main.class);
 public static void main(String[] args) {
  Map ma=new HashMap();
  ma.put("sendtime","20160503");
  //連接impala查庫(kù),返回List<People>,其中peopel為自定義實(shí)體類
  List<People> peopleList=ImpalaJdbc.connImpala();
  if(peopleList.size()==0){
   logger.info("peopleList.size()==0");
  }
  ma.put("data",peopleList);
  ObjectMapper om=new ObjectMapper();
  try {
   String jsonStr=om.writeValueAsString(ma);
   System.out.println(jsonStr);
   CloseableHttpResponse httpResponse=null;
   CloseableHttpClient httpClient= HttpClientBuilder.create().setRetryHandler(new DefaultHttpRequestRetryHandler()).build();
   //解決中文亂碼,注意與服務(wù)端同時(shí)存在
   StringEntity stringEntity=new StringEntity(jsonStr,"UTF-8");
  //就目前來(lái)說(shuō)下面這段代碼是可有可無(wú) stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
  //post 地址
   HttpUriRequest httpUriRequest= RequestBuilder.post("http://localhost:8080/qc").setEntity(stringEntity).build();
  httpResponse=httpClient.execute(httpUriRequest);
   System.out.println("發(fā)送");
   int statusCode=httpResponse.getStatusLine().getStatusCode();
   if(statusCode== HttpStatus.SC_OK){
//    HttpEntity entity = httpResponse.getEntity();
//    InputStream in =entity.getContent();
    System.out.println("文件傳輸服務(wù)器正常響應(yīng)!");
   }
  } catch (JsonProcessingException e) {
   e.printStackTrace();
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  } catch (ClientProtocolException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

服務(wù)端

采用最原始的servlet

import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
/**
 * Created by 小省.
 */
public class QcServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
doGet(request,response);
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
System.out.println("+++++++++++++++++++");
//解決中文亂碼
BufferedReader br =new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
String line=null;
StringBuffer sb =new StringBuffer();
while ((line=br.readLine())!=null){
sb.append(line);
}
System.out.println("sb.toString()"+sb.toString());
//就目前而言String reesult = URLDecoder.decode(sb.toString(), HTTP.UTF_8);是可有可無(wú)的,httpclient會(huì)自動(dòng)解碼
//String reesult =sb.toString();
String reesult = URLDecoder.decode(sb.toString(), HTTP.UTF_8);
try {
//將string 字符串轉(zhuǎn)化為json數(shù)組,并且遍歷
JSONObject jsonObject =new JSONObject(reesult);
String mesage=(String) jsonObject.getString("data");
JSONArray myJsonArray = new JSONArray(mesage);
for(int i=0 ; i < myJsonArray.length() ;i++){
//獲取每一個(gè)JsonObject對(duì)象
JSONObject myjObject = myJsonArray.getJSONObject(i);
System.out.println(myjObject.getString("name"));
}
System.out.println(reesult);
} catch (JSONException e) {
e.printStackTrace();
}
}
}

看完上述內(nèi)容,你們對(duì)使用httpclient對(duì)json數(shù)據(jù)進(jìn)行傳遞時(shí)出現(xiàn)亂碼如何解決有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI