问题描述:通过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