我有一个Android应用程序,用于响应回复JSON响应的Web查询。当查询格式正确时,一切正常。但是,当查询错误时,代码崩溃,我在堆栈跟踪中得到以下内容:
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;
}
答案 0 :(得分:0)
您可以使用以下代码检查httpurlconnection对象的状态代码:
if(conn.getResponseCode()==HttpURLConnection.HTTP_ACCEPTED)
{
//handle the accepted response
}
else
{
//handle the failed response
}
答案 1 :(得分:0)
您应该使用getErrorStream()
来读取后端调用的错误流
如果出现错误,则从服务器返回输入流 因为在远程服务器上找不到请求的文件。这个 stream可用于读取服务器将发回的数据。
InputStream is = null;
if (responseCode == 200) {
is = urlConnection.getInputStream();
} else {
is = urlConnection.getErrorStream();
}
答案 2 :(得分:0)
使用以下代码来获取json响应表单服务器:
private InputStream is = null;
private String jsonString = "";
private JSONObject jsonObj = null;
public JSONObject getJSONFromUrl(final String url) { //url is your url
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
if (sb.length() != 0)
jsonString = sb.toString();
} catch (Exception e) {
Log.e("_TAG", "Buffer Error: " + e.getMessage());
}
try {
jsonObj = new JSONObject(jsonString);
} catch (JSONException e) {
Log.e("_TAG", "Parsing Error: " + e.getMessage());
}
return jsonObj;
}
现在通过上面的方法从返回的jsonObj获取 statusCode 。