我有一个异步任务,不断向服务器发送消息并接收消息作为回报。当我测试它时,我让它运行几秒钟,然后关掉wifi。该应用程序然后崩溃并发送空指针异常。我能够在HTTPPost中做任何事情,或者只是在没有互联网而不是崩溃应用程序的情况下发送消息?Android HTTP Post返回null
这是我的代码
private class UpdateLoc extends AsyncTask<Void,Void,String> {
InputStream inputStream = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try{
if(s.trim()!=null){
Log.d("HTTPRESULT",s.toString());
}
}catch (Exception e){
e.printStackTrace();
}
}
@Override
protected String doInBackground(Void... params) {
String result = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Constants.UPDATE);
List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair(Constants.params_email,email));
nameValuePairs.add(new BasicNameValuePair(Constants.params_location,curr_location));
try{
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"),8);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while((line=bufferedReader.readLine())!=null){
stringBuilder.append(line+"\n");
}
result = stringBuilder.toString();
}catch (ClientProtocolException e){
e.printStackTrace();
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return result;
}
}
在调用任务之前运行互联网连接检查? – SQLiteNoob
会减慢应用程序的速度吗?我想每5秒钟调用一次。 – JianYA
也正如你已经捕捉到一些例外。你为什么不对NullPointerException做同样的事情? – Salem