【问题标题】:Android POST Request 400 Response code throws ExceptionAndroid POST 请求 400 响应代码抛出异常
【发布时间】:2012-08-15 10:50:30
【问题描述】:

当我向服务器发送 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;

亲切的问候,

【问题讨论】:

    标签: java android post http-status-code-400


    【解决方案1】:

    为此使用getErrorStream()。来自docs

    如果 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);
            }
    

    【讨论】:

    • httpURLConnection.getErrorStream() 的好答案 +1,因为它有助于读取错误内容作为响应...
    【解决方案2】:

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

    【讨论】:

    • 所以服务器向我发送带有 400 响应代码的信息。我怎么读?
    • 这是非常基本的东西,伙计,只需在建立连接时检查响应代码并自己处理响应即可。例如,如果您最终得到的结果不是 200,您应该向用户显示某种消息,并且不要继续尝试阅读响应。
    • 我们的服务器的设计方式是,如果请求参数不正确,比如用户提供了错误的用户名或密码,则会生成 400 响应代码。在这种情况下,服务器会发送带有生成的错误消息的 json 响应。所以我也必须阅读这种情况下的回复。我该怎么做?
    • 是的,不是读取 InputStream,而是解析 ErrorStream 中提供的 json (getErrorStream())
    【解决方案3】:

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

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

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

        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();
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      相关资源
      最近更新 更多