【问题标题】:Android HttpUrlConnection Post Method - Json - Laravel API response on ErrorAndroid HttpUrlConnection Post 方法 - Json - Laravel API 对错误的响应
【发布时间】:2023-03-12 14:58:01
【问题描述】:

我在 laravel 中写了一个 API,用于接受 POST 请求接收参数并保存在 DB 中。

成功时,它会返回一个 json,返回订单 ID(Http 响应代码 200)

{
    "data": {
        "order_id": 21
    }
}

在将数据保存到 DB 之前,我会验证数据,如果有 错误,它会返回错误消息 json(Http 响应代码 400)

{
    "error": {
        "code": "GEN-WRONG-ARGS",
        "http_code": 400,
        "message": {
            "cust_id": [
                "The cust id may not be greater than 9999999999."
            ]
        }
    }
}

在浏览器中运行良好

在 Android 通话中,如果一切正常,例如http 响应代码 200 我得到了 json。

但是当返回错误 json 时,我从未收到错误 json,getInputStream() 返回 null。

private InputStream downloadUrl(String urlString) throws IOException {
    // BEGIN_INCLUDE(get_inputstream)
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Start the query
    conn.connect();
    InputStream stream = conn.getInputStream();
    return stream;
    // END_INCLUDE(get_inputstream)
}
  1. 如果出现错误,如何将响应代码更改为 200 并在 Laravel 中发送,然后获取错误 json。
  2. 或在 Android 中即使有响应代码如 400 或 404,我也能收到 http 正文,就像浏览器一样

1 是一种解决方法,2 是正确的方法。

谢谢,

K

【问题讨论】:

  • 有人可以帮忙吗?

标签: android api http laravel


【解决方案1】:

经过数小时的努力,我找到了解决方案。 getErrorStream() 是解决此问题的方法。如果响应代码> = 400,我将代码更改如下以获得错误响应。

private InputStream downloadUrl(String urlString) throws IOException {
// BEGIN_INCLUDE(get_inputstream)
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Start the query
conn.connect();
InputStream stream  = null;
    try {
        //Get Response
        stream = conn.getInputStream();
    } catch (Exception e) {
        try {
            int responseCode = conn.getResponseCode();
            if (responseCode >= 400 && responseCode < 500)
                stream = conn.getErrorStream();
            else throw e;
        } catch (Exception es) {
            throw es;
        }
    }
return stream;
// END_INCLUDE(get_inputstream)
}

希望这会为某人节省大量时间

谢谢, 克

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-05
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多