当我建立了网络连接时,以下代码正常工作。我想从一个站点获取一个json字符串,但是当Internet无法工作或没有可用的数据连接时,无法提供适当的异常处理。你能帮我处理例外情况吗?因为,我已经尝试了很多但没有成功。提前谢谢!
public JSONObject makeHttpRequest(String url, List<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = null;
try{
httpResponse = httpClient.execute(httpPost);}
catch(NullPointerException e){
Log.d("nullpoint","check");
e.printStackTrace();
}
int status=httpResponse.getStatusLine().getStatusCode();
if(status==200){
HttpEntity httpEntity = httpResponse.getEntity();
String data=EntityUtils.toString(httpEntity);
json=data.split("<!--")[0];
Log.d("Json",json);
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}