Android HTTP Post返回null

时间:2016-06-11 11:52:10

标签: android

我有一个异步任务,它不断向服务器发送消息并接收消息作为回报。当我测试它时,我让它运行几秒钟,然后关闭wifi。该应用程序然后崩溃并发送空指针异常。我能在HTTPPost中做任何事情,甚至只是在没有互联网而不是崩溃应用程序时发送消息吗?

这是我的代码

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;
        }
    }

1 个答案:

答案 0 :(得分:0)

在调用AsyncTask之前尝试检查网络连接,例如:

private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

=======

您可以找到文档here