即使我们有错误代码响应,如何获取内容

时间:2015-02-27 13:57:28

标签: java java-ee

我像这样创建HTTP GET:

URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

工作棒极了!但想象一下,服务器返回错误201或错误206.如何获得响应内容甚至错误代码不是200?我不想使用另一个库,我想使用HttpURLConnection

来做这个

1 个答案:

答案 0 :(得分:0)

BufferedReader rd = null;

        if (urlConnection.getResponseCode() == 200) {
            rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        } else {
            rd = new BufferedReader(new InputStreamReader(urlConnection.getErrorStream()));
        }

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }