2016-05-23 73 views
1

我有一個POST請求,由客戶端 - 它可能是這個樣子:HTTP錯誤代碼,導致IOException - 如何訪問響應?

https://www.pollmc.com/api/v1/poll.php 
PARAMS 
    question = Question 
    answers = ["Yes","No"] 
    oip = true 
    secret = false 
    displayname = Chris 

而且我在做一個測試,我已經禁止自己(返回403錯誤)。但是,當它返回錯誤時,java會導致IOException錯誤(在我的嘗試& catch中)。我該如何阻止它導致錯誤,或得到響應,以便我可以將它發送給客戶端,告訴他們他們做錯了什麼。

這是我的代碼

try { 
     urlParams = URLEncoder.encode(urlParams, "UTF-8"); 

     URL urlObject = new URL(url); 
     HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection(); 
     connection.setDoOutput(true); 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
     connection.setRequestProperty("Content-Length", String.valueOf(urlParams.length())); 
     connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0"); 

     OutputStream os = connection.getOutputStream(); 
     os.write(urlParams.getBytes()); 

     StringBuilder responseSB = new StringBuilder(); 
     BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); 

     String line; 
     while ((line = br.readLine()) != null) 
      responseSB.append(line); 

     br.close(); 
     os.close(); 

     this.response = responseSB.toString(); 
     this.responseCode = connection.getResponseCode(); 
    } catch(IOException e) { 
     e.printStackTrace(); 
    } 
+0

開始通過找出哪一行引起該問題 –

回答

1

只需檢查該請求是否是讀取響應之前成功的,所述邏輯執行以下操作:

if (connection.getResponseCode() >= 200 && connection.getResponseCode() < 400) 
    // then read connection.getInputStream() 
else 
    // then read connection.getErrorStream() 
+0

謝謝!我嘗試了各種各樣的東西,但你的瞬間工作;)愛你(沒有同性戀) – JustRayz

+0

@JustRayz好消息 –