1. 程式人生 > >關於java.io.IOException: Server returned HTTP response code: 400 for URL報錯和string.getBytes()字符集

關於java.io.IOException: Server returned HTTP response code: 400 for URL報錯和string.getBytes()字符集

cep amr 單引號 驗證 sco app response spa tin

400 請求出錯:由於語法格式有誤,服務器無法理解此請求
總論:這種錯誤應該會有很多原因,這裏指出的是因為字符集編碼的原因導致400,主要代碼:向服務器發送請求傳輸json參數用的是out.write(json.getBytes())(讀取的是操作系統的字符集,如果操作系統與部署項目的服務器不同則報錯);改為out.writeChars(json);或out.write(json.getBytes(服務器編碼))即可。如下代碼16行

 1             //創建連接             
 2             URL url = new URL(u);
 3             HttpURLConnection connection = (HttpURLConnection) url.openConnection();
4 connection.setDoOutput(true); 5 connection.setDoInput(true); 6 connection.setRequestMethod("POST"); 7 connection.setRequestProperty("connection", "keep-alive"); 8 connection.setConnectTimeout(30000); 9 connection.setReadTimeout(30000);
10 connection.setUseCaches(false); 11 connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); 12 connection.connect(); 13 // POST請求 14 out = new DataOutputStream(connection.getOutputStream()); 15 String json = message.toString();
16 out.writeChars(json); // 這行是關鍵我之前寫的是 out.write(json.getBytes()); 17 System.out.println(json); 18 out.flush(); 19 // 讀取響應 20 reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 21 String lines; 22 StringBuffer sb = new StringBuffer(""); 23 while ((lines = reader.readLine()) != null) { 24 lines = new String(lines.getBytes(), "utf-8"); 25 sb.append(lines); 26 } 27 JSONObject jsStr =JSONObject.fromObject(sb.toString()); 28 //獲取響應值,判斷是否驗證通過 29 String code = (String) jsStr.get("code"); 30 String msg=(String) jsStr.get("msg"); 31 System.out.println("code:"+code+",msg:"+msg); 32 //接口返回驗證數據是否通過 33 if("0".equals(code)){ 34 result = "success"; 35 } else{ 36 result = "fail"; 37 System.out.println("下發出錯:錯誤原因為" + msg + "下發內容為:" + json); 38 } 39 reader.close(); 40 // 斷開連接 41 connection.disconnect(); 42

這其中也經過一些波折,比如在自己的eclipse上運行正常,部署到服務器上就不行了,json數據是一樣的但是因為自己本地的服務器和部署項目的服務器編碼不同,而產生這種錯誤。

在解決問題時百度做了很久,因為不適應我的項目做了一些錯誤的更改,比如找空格,在我的json中是存在空格的,但是我用的是post提交,並不會有影響。還有說要雙引號轉成單引號的,這讓原本本地不報錯的程序也報錯了,可是我還傻傻的開心以為是引號的事。還有讓轉json編碼的,但是無論json轉成什麽格編碼out.write(json.getBytes()) 傳輸的時候編碼格式沒有設定,還是去默認操作系統的編碼還是不會改對

關於java.io.IOException: Server returned HTTP response code: 400 for URL報錯和string.getBytes()字符集