Android POST请求400响应代码抛出异常

And*_*Dev 2 java post android http-status-code-400

当我向服务器发送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;
Run Code Online (Sandbox Code Playgroud)

亲切的问候,

Car*_*ann 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);
        }
Run Code Online (Sandbox Code Playgroud)