首页 文章

Android HttpUrlConnection Post方法 - Json - 错误的Laravel API响应

提问于
浏览
0

我在laravel中编写了一个API,接受POST请求以接收参数并将其保存在DB中 .

success 上,它返回一个返回订单ID的json(Http响应代码200)

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

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

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

It works perfectly fine in browser

在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)
}
  • 如果有错误,我如何将响应代码更改为200并将其发送到 Laravel 然后获取错误json .

  • Android 哇我可以收到http正文,即使有像400或404这样的响应代码,比如浏览器获取

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

谢谢,

ķ

1 回答

  • 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)
    }
    

    希望这能节省大量时间

    谢谢,K

相关问题