生活随笔
收集整理的這篇文章主要介紹了
POST请求传入中文参数,接收端乱码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題描述:通過post請求調試短信接口發送出去后,客戶端無法收到短信,中文內容亂碼
追蹤過程:
接口采用post請求進行,無法收取短信的接口代碼如下: public static String sendPost(String url, Map<String, String> paramMap) {PrintWriter out = null;BufferedReader in = null;String result = "";try {URL realUrl = new URL(url);// 打開和URL之間的連接URLConnection conn = realUrl.openConnection();// 設置通用的請求屬性conn.setRequestProperty("accept", "*/*");conn.setRequestProperty("connection", "Keep-Alive");conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");conn.setRequestProperty("Charset", "UTF-8");// 發送POST請求必須設置如下兩行conn.setDoOutput(true);conn.setDoInput(true);// 獲取URLConnection對象對應的輸出流out = new PrintWriter(conn.getOutputStream());// 設置請求屬性StringBuilder param = new StringBuilder();if (paramMap != null && paramMap.size() > 0) {Iterator<String> ite = paramMap.keySet().iterator();while (ite.hasNext()) {String key = ite.next();// keyString value = paramMap.get(key);param.append(key).append("=").append(value).append("&");}param = new StringBuilder(param.substring(0, param.length() - 1));}// 發送請求參數out.print(param);// flush輸出流的緩沖out.flush();// 定義BufferedReader輸入流來讀取URL的響應in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {System.err.println("發送 POST 請求出現異常!" + e);e.printStackTrace();}// 使用finally塊來關閉輸出流、輸入流finally {try {if (out != null) {out.close();}if (in != null) {in.close();}} catch (IOException ex) {ex.printStackTrace();}}return result;} 其中的參數paramMap如下:
?
Map<String, String> params = new HashMap<String, String>();params.put("userid", userid);params.put("ts", ts);params.put("sign", md5.toLowerCase());params.put("mobile", phones);params.put("msgcontent", "【您好!請注意】" + content);params.put("extnum", sendtermid);params.put("time", sendtime); 問題的源頭是其中的key 為msgContent的value中含有中文,而中文內容如果不通過URLEncoder.encode(param,"UTF-8"),"UTF-8")進行編碼設置,那么會被默認的通過其他編碼格式進行編碼后發送出去,導致短信平臺服務器接收到的短信內容是亂碼
解決方案:在入參時進行UTF-8編碼處理
URLEncoder.encode(URLEncoder.encode(param,"UTF-8"),"UTF-8"))
服務端獲取參數時進行一次解碼
String param= URLDecoder.decode(param, "UTF-8");
感謝文章:https://my.oschina.net/gschen/blog/120553?
https://www.zhongjianghua.com/att1tude/131194-2020-12.html
總結
以上是生活随笔為你收集整理的POST请求传入中文参数,接收端乱码的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。