我有一個異步任務,不斷向服務器發送消息並接收消息作爲回報。當我測試它時,我讓它運行幾秒鐘,然後關掉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