在綁定用戶微信時,需要從微信獲取用戶信息,此處容易出現亂碼。
JSONObject jo = this.getAccessTokenOpenid(code); StringBuilder sb = new StringBuilder("https://api.weixin.qq.com/sns/userinfo?access_token="); sb.append(jo.getString("access_token")); sb.append("&openid=").append(jo.getString("openid")).append("&lang=zh_CN"); HttpMethod method = new PostMethod(sb.toString()); HttpClient httpclient = new HttpClient(); httpclient.executeMethod(method); String result = new String(method.getResponseBody(), "utf-8"); // String result = method.getResponseBodyAsString();
System.out.println("getWeiXinUserInfo result = " + result); JSONObject userInfo = JSON.parseObject(result, JSONObject.class);
將 String result = method.getResponseBodyAsString();
換成 String result = new String(method.getResponseBody(), "utf-8");
即可。
method.getResponseBodyAsString():
Returns the response body of the HTTP method, if any, as a String. If response body is not available or cannot be read, null is returned. The raw bytes in the body are converted to a String using the character encoding specified in the response's Content-Type header, or ISO-8859-1 if the response did not specify a character set.
Note that this method does not propagate I/O exceptions. If an error occurs while reading the body, null will be returned.
而:new String(method.getResponseBody(), "utf-8")
將 method.getResponseBody() 返回的原生字節用指定的 utf-8 編碼,編碼成String。因為微信的返回值就是采用的utf-8編碼。
運行結果:

沒有亂碼出現。
