java获取参数编码_java获取接口数据编码问题
需求比較簡單,就是獲取接口數據并返回。但是在用的過程中發現編碼問題。接口返回的數據編碼為UTF-8,希望顯示的數據也是UTF-8,問題出在從輸入流中讀取數據的過程中。下面是幾個實例程序。
1、不管編碼,直接寫
public static String sendGet(String url , String param) {
String result = "";
try{
String urlName = url + "?" + param;
URL realUrl = new URL(urlName);
HttpURLConnection conn = (HttpURLConnection)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.connect();
BufferedReader?in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while((line = in.readLine()) != null){
result += line;
}
}catch(Exception e){
System.out.println("get出錯了" + e);
e.printStackTrace();
}
finally{
try{
if(in != null){
in.close();
}
}catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
這個時候,返回數據優于編碼不對,呈現亂碼狀態。下面進行修改。
2、第一次修改
第一次修改,是將獲取到的result按照如下方法進行重新編碼:
byte[] bs = result.getBytes();
result = new String(bs,"UTF-8");
修改后大部分數據編碼正確,但是仍舊有部分不對,顯示為???。多次嘗試此方式,包括將result.getBytes()修改為result.getBytes(""UTF-8)都失敗。
3、修改完成
最后發現應該在創建BufferedReader時候,加入編碼,即將
BufferedReader?in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
修改為:
BufferedReader?in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
編碼正常。
總結
以上是生活随笔為你收集整理的java获取参数编码_java获取接口数据编码问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 拟合与岭回归
- 下一篇: c语言表达式10 amp 6等于多少,C