gpt4 book ai didi

android - 使用 JSON 时如何处理 500 Internal Server Error

转载 作者:可可西里 更新时间:2023-10-31 22:05:12 24 4
gpt4 key购买 nike

我是 Android 的新手,我正在使用 JSON 从服务器获取数据。在第 22 行的第一个循环中,StringBuilder 包含 500 Internal Server Error,然后 jArray 最终返回 null。我该如何处理这个错误?

public static JSONObject getJSON() {
String jsonString = "";
InputStream inStream = null;

//http post
JSONObject jArray = null;
try {
HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httpPost = new HttpPost(WS_URL);
httpPost.setHeader("Content-type", "application/json");

HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
inStream = entity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();

String line = null;

while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inStream.close();
jsonString = sb.toString();

jArray = new JSONObject(jsonString);


//outputTransactions(jArray);

} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

return jArray;
}

最佳答案

虽然回复晚了,但可能对其他人有帮助。在将其解析为 JSON 之前,您需要检查服务器的响应状态。

例如

int status_code=response.getStatusLine().getStatusCode();

if(status_code!=200){
Log.d("MYLOG","ERROR! Response status is"+status_code);
}
else{
inStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();

String line = null;

while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inStream.close();


// Rest of your code......
}

或者您可以选择检查状态代码并向用户显示错误

喜欢:

else if(status_code==404){
Log.d("MYLOG","Sorry! Page not found! Check the URL ");

}else if(status_code==500){
Log.d("MYLOG","Server is not responding! Sorry try again later..");
}

希望对像你这样的新手有所帮助:-)

关于android - 使用 JSON 时如何处理 500 Internal Server Error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28786388/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com