【发布时间】:2015-04-30 11:40:32
【问题描述】:
我有一个 Android 应用程序,它是为响应一个响应 JSON 响应的网络查询而编写的。当查询格式正确时,一切正常。但是,当查询错误时,代码崩溃,我在堆栈跟踪中得到以下信息:
java.io.FileNotFoundException: https://******
我已将***** 代替我在此处放置的隐私查询。
如果我在浏览器中输入相同的查询,我会得到以下响应:
{"statusCode":401,"error":"Unauthorized","message":"Missing authentication"}
我的问题是 - 为什么我的代码会抛出错误,而不是将其视为可以解析的有效 JSON 响应?
这是我的代码:
@Override
protected String doInBackground(String... params) {
try {
URL u = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestMethod("GET");
conn.connect();
InputStream is = conn.getInputStream();
// Read the stream
byte[] b = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ( is.read(b) != -1) {
baos.write(b);
}
String JSONResp = new String(baos.toByteArray());
return JSONResp;
}
catch(Throwable t) {
t.printStackTrace();
}
return null;
}
【问题讨论】:
标签: android json http http-status-code-404