我在laravel中编写了一个API,接受POST请求以接收参数并将其保存在DB中。
在成功时,它会返回一个返回订单ID的json(Http响应代码200)
{
"data": {
"order_id": 21
}
}
在将数据保存到数据库之前我验证数据,如果有错误,则返回错误消息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是一种解决方法,2是正确的方法。
谢谢,
ķ
答案 0 :(得分: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)
}
希望这能节省大量时间
谢谢, ķ