HTTP错误代码,导致IOException - 如何访问响应?

时间:2016-05-23 18:01:07

标签: java http

我有一个由客户提出的POST请求 - 它看起来像这样:

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

我正在做一个测试,我已经禁止自己(返回403错误)。但是,当它确实返回错误时,java会导致IOException错误(在我的try& 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();
    }

1 个答案:

答案 0 :(得分:0)

在阅读回复之前,只需检查请求是否成功,逻辑如下:

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