2

当我向服务器发送 POST 请求时,如果响应为 200,我会得到 JSON 正文。但是,对于不成功的请求,服务器会发送 400 响应代码,但我的 android 代码会引发 FileNotFoundException。阅读 400 响应和 200 响应之间有什么区别吗?

        StringBuffer responseBuilder = new StringBuffer();
    String line = null;
    HttpURLConnection conn = null;
    OutputStream out = null;
    BufferedReader rd = null;
    System.setProperty("http.keepAlive", "false");
    try
    {
        conn = (HttpURLConnection) new URL(requestURL).openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setConnectTimeout(NetworkConstants.CONNECTION_TIMEOUT);
        conn.setReadTimeout(NetworkConstants.SOCKET_TIMEOUT);

        out = conn.getOutputStream();
        Writer writer = new OutputStreamWriter(out, "UTF-8");
        String s = formatParams();
        Log.d("-------------------------------------------------->", s);
        writer.write(s);
        writer.flush();
        writer.close();
    }

    catch (Exception e)
    {

    }

    finally
    {
        if (out != null)
        {
            try
            {
                out.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();

            }
        }
    }
    try
    {
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = rd.readLine()) != null)
        {
            responseBuilder.append(line);
            if (!rd.ready())
            {
                break;
            }
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    finally
    {
        if (conn != null)
        {
            conn.disconnect();
        }
    }

    String response = responseBuilder.toString();
    Log.d("@@@@@@@@@@@@@@@@@@@@@@@@@@@", response);
    return response;

亲切的问候,

4

3 回答 3

5

用于getErrorStream()此。从文档

如果 HTTP 响应表明发生了错误,getInputStream()将抛出一个IOException. 用于getErrorStream()读取错误响应。可以使用正常方式读取标题getHeaderFields()

示例代码:

        httpURLConnection.connect();

        int responseCode = httpURLConnection.getResponseCode();
        if (responseCode >= 400 && responseCode <= 499) {
            Log.e(TAG, "HTTPx Response: " + responseCode + " - " + httpURLConnection.getResponseMessage());
            in = new BufferedInputStream(httpURLConnection.getErrorStream());
        }
        else {
            in = new BufferedInputStream(httpURLConnection.getInputStream());
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            urlResponse.append(line);
        }
于 2015-12-04T02:03:28.700 回答
0

如果响应代码不是 200 或 2xx,请使用 getErrorStream() 而不是 getInputStream() 来解析 json 并显示后端提供的消息。

于 2012-08-15T10:55:47.337 回答
0

我知道这个问题已经有很长时间了,但为了其他仍然遇到此类问题的人的利益,请注意问题的另一个可能原因是使用“connection.getContent()”来获取 InputStream。
像这样:

InputStream is = (InputStream) connection.getContent();

这可能会产生一个问题,即根本不会处理大于 399 的响应代码。
因此建议直接使用 getInputStream() 和 getErrorStream() ,如前面的评论和以下示例所示:

    HttpURLConnection connection = null;
    BufferedReader bufferedReader = null;
    try {
        String urlString = "http://www.someurl.com";
        URL url = new URL(urlString);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        InputStream is;
        int responseCode = connection.getResponseCode();
        if (responseCode < HttpURLConnection.HTTP_BAD_REQUEST) {
            is = connection.getInputStream();
        } else {
            is = connection.getErrorStream();
        }

        StringBuilder response = new StringBuilder();
        bufferedReader = new BufferedReader(new InputStreamReader(is));
        String tempLine;
        while ((tempLine = bufferedReader.readLine()) != null) {
            response.append(tempLine);
        }
        String serverResponse = response.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            connection.disconnect();
        }
    }
于 2019-12-07T22:23:01.050 回答