做過微信開發的人應該都會接觸到授權登錄、獲取用戶信息等操作,比如獲取用戶信息,騰訊要求以get請求提交,返回的是json字符串。
通常我們使用的方法是用HttpURLConnection去調用接口,打開http連接,從連接讀取返回的參數。
但是有時候(本人的開發環境沒問題,部署到linux服務器上后存在亂碼問題)接收到的json字符串中文字符變成亂碼。
以下是我的代碼
try { System.out.println("訪問GET請求:" + url1); HttpURLConnection httpConn = null; BufferedReader in = null; try { URL url = new URL(url1); httpConn = (HttpURLConnection) url.openConnection(); // 讀取響應 if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) { StringBuffer content = new StringBuffer();
String tempStr = ""; in = new BufferedReader(new InputStreamReader( httpConn.getInputStream())); while ((tempStr = in.readLine()) != null) { content.append(tempStr);
}
return JSONObject.fromObject(content.toString()); } else { throw new Exception("請求出現了問題!");
} } catch (IOException e) { e.printStackTrace(); } finally { in.close();
httpConn.disconnect(); } } catch (Exception e) { e.printStackTrace();
}
其實這種做法只需要從輸入流讀取參數的時候指定讀取的數據的編碼格式即可,代碼為
in = new BufferedReader(new InputStreamReader(
httpConn.getInputStream(),"UTF-8"));
如此上述亂碼問題解決。
還有,在我們發送POST請求時,如調用自定義菜單、推送消息等接口時,需要發送參數,代碼如下
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)");
// 發送POST請求必須設置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
out = new PrintWriter(conn.getOutputStream());
// 發送請求參數
out.print(param);
// flush輸出流的緩沖
out.flush();
其中param是參數,這樣param中存在中文參數時,也會出現亂碼,比如公眾號的自定義菜單變成亂碼等。解決辦法與上面類似
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
將輸出流中的參數指定編碼格式,亂碼問題解決。