java调用 restapi 乱码_Java HttpURLConnection模拟请求Rest接口解决中文乱码问题
public staticString PostRequest(String URL,String obj) {
String jsonString="";try{//創建連接
URL url = newURL(URL);
HttpURLConnection connection=(HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST"); //設置請求方法
connection.setRequestProperty("Charsert", "UTF-8"); //設置請求編碼
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type","application/json");
connection.connect();//POST請求
DataOutputStream out = newDataOutputStream(
connection.getOutputStream());//關鍵的一步
out.writeBytes(obj);
out.flush();
out.close();//讀取響應
if (connection.getResponseCode()==200) {
BufferedReader reader= new BufferedReader(newInputStreamReader(connection.getInputStream()));
String lines;
StringBuffer sb= new StringBuffer("");while ((lines = reader.readLine()) != null) {
lines= new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
jsonString=sb.toString();
reader.close();
}//返回值為200輸出正確的響應信息
if (connection.getResponseCode()==400) {
BufferedReader reader= new BufferedReader(newInputStreamReader(connection.getErrorStream()));
String lines;
StringBuffer sb= new StringBuffer("");while ((lines = reader.readLine()) != null) {
lines= new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
jsonString=sb.toString();
reader.close();
}//返回值錯誤,輸出錯誤的返回信息//斷開連接
connection.disconnect();
}catch(MalformedURLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(UnsupportedEncodingException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e) {//TODO Auto-generated catch block
e.printStackTrace();
}returnjsonString;
}
總結
以上是生活随笔為你收集整理的java调用 restapi 乱码_Java HttpURLConnection模拟请求Rest接口解决中文乱码问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: microstation添加txt文件_
- 下一篇: java美元兑换,(Java实现) 美元