当我尝试将json数据发布到Web服务时,Android应用程序崩溃

时间:2014-08-08 11:28:43

标签: java android json http post

大家好我试图将数据从我的Android应用程序发送到json对象中的Web服务,但是当我点击发送按钮时应用程序崩溃任何人都可以帮助我解决我的问题? thx,下面是我的主要java代码:

public  class MainActivity extends Activity  {

private Button send;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);

   send= (Button)findViewById(R.id.btnSend);
   send.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

            JSONObject jsonobj; // declared locally so that it destroys after serving  its purpose
            jsonobj = new JSONObject();
            try {
                // adding some keys
                jsonobj.put("name", "toto");
                jsonobj.put("twitter", "twito");
                jsonobj.put("country", "totoland");                     
            } catch (JSONException ex) {
                //buildref.setText("Error Occurred while building JSON");
                ex.printStackTrace();
            }
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httppostreq = new HttpPost("bbqhmkcode.appspot.com/jsonservlet");
            StringEntity se = null;
            try {
                se = new StringEntity(jsonobj.toString());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            se.setContentType("application/json;charset=UTF-8");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
            httppostreq.setEntity(se);
            try {
                HttpResponse httpresponse = httpclient.execute(httppostreq);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
 }
}

这是LogCat:

    08-08 15:11:51.790: I/Process(24024): Sending signal. PID: 24024 SIG: 9
    08-08 15:12:34.440: W/dalvikvm(24321): threadid=11: thread exiting with uncaught                             exception (group=0x41d3e700)
  08-08 15:12:34.510: E/AndroidRuntime(24321): FATAL EXCEPTION: AsyncTask #1
  08-08 15:12:34.510: E/AndroidRuntime(24321): java.lang.RuntimeException: An error occured while executing doInBackground()
 08-08 15:12:34.510: E/AndroidRuntime(24321):   at android.os.AsyncTask$3.done(AsyncTask.java:299)
 08-08 15:12:34.510: E/AndroidRuntime(24321):   at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
 08-08 15:12:34.510: E/AndroidRuntime(24321):   at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
 08-08 15:12:34.510: E/AndroidRuntime(24321):   at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-08 15:12:34.510: E/AndroidRuntime(24321):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-08 15:12:34.510: E/AndroidRuntime(24321):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-08 15:12:34.510: E/AndroidRuntime(24321):    at java.lang.Thread.run(Thread.java:841)
08-08 15:12:34.510: E/AndroidRuntime(24321): Caused by: java.lang.NullPointerException
08-08 15:12:34.510: E/AndroidRuntime(24321):    at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:518)
08-08 15:12:34.510: E/AndroidRuntime(24321):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)

08-08 15:12:34.510:E / AndroidRuntime(24321):at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)    08-08 15:12:34.510:E / AndroidRuntime(24321):at com.example.MainActivity $ HttpAsyncTask.doInBackground(MainActivity.java:72)    08-08 15:12:34.510:E / AndroidRuntime(24321):at com.example.MainActivity $ HttpAsyncTask.doInBackground(MainActivity.java:1)    08-08 15:12:34.510:E / AndroidRuntime(24321):在android.os.AsyncTask $ 2.call(AsyncTask.java:287)    08-08 15:12:34.510:E / AndroidRuntime(24321):at java.util.concurrent.FutureTask.run(FutureTask.java:234)

3 个答案:

答案 0 :(得分:1)

您正在从主UI线程发送数据。尝试使用AsyncTask<>发送数据 像这样

public  class MainActivity extends Activity  {

private Button send;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);



send= (Button)findViewById(R.id.btnSend);
send.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
     // execute like this way
         new HttpAsyncTask().execute("bbqhmkcode.appspot.com/jsonservlet");


 });
}


  private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

           JSONObject jsonobj; // declared locally so that it destroys after serving  its purpose
               jsonobj = new JSONObject();
               try {
                   // adding some keys
                    jsonobj.put("name", "toto");
                    jsonobj.put("twitter", "twito");
                    jsonobj.put("country", "totoland");                     
                } catch (JSONException ex) {
                    //buildref.setText("Error Occurred while building JSON");
                    ex.printStackTrace();
                }
                DefaultHttpClient httpclient = new DefaultHttpClient();
                HttpPost httppostreq = new HttpPost();
                StringEntity se = null;
                try {
                    se = new StringEntity(jsonobj.toString());
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                se.setContentType("application/json;charset=UTF-8");
                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
               httppostreq.setEntity(se);

                    HttpResponse httpresponse = httpclient.execute(httppostreq);
                    InputStream inputStream = httpResponse.getEntity().getContent();
                    if(inputStream != null)
                         result = convertInputStreamToString(inputStream);
                    else
                         result = "Did not work!";

      return result;
    }

   private String convertInputStreamToString(InputStream inputStream) throws IOException {
        // TODO Auto-generated method stub

        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        return result;

    }

}


        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
                //you will get result here in "result"
       }
    }

}

我已编辑了您的代码,但您可能需要更正其格式 这就是我按照自己的方式使用的方式

    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {



            return POST(urls[0]);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
       }
    }
    public static String POST(String url){
    InputStream inputStream = null;
    String result = "";
    try {

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("name", "jaimin");
        jsonObject.accumulate("country","ind");
        jsonObject.accumulate("twitter", "yoooo");

        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();



      // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content   
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }
   // 11. return result
    return result;

  }

private static String convertInputStreamToString(InputStream inputStream) throws IOException {
    // TODO Auto-generated method stub

    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

  }
  public boolean isConnected() {
    // TODO Auto-generated method stub
     ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
      NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
      if (networkInfo != null && networkInfo.isConnected()) 
         return true;
      else
         return false;  
 } 

答案 1 :(得分:0)

Read about runOnUiThread. Call this runThread() method name into the onCreate().
private void runThread(){
 runOnUiThread (new Thread(new Runnable() { 
     public void run() {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppostreq = new HttpPost("bbqhmkcode.appspot.com/jsonservlet");
        StringEntity se = null;
        httppostreq.setEntity(se);
        try {  se = new StringEntity(jsonobj.toString());
               se.setContentType("application/json;charset=UTF-8");
               se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
               HttpResponse httpresponse = httpclient.execute(httppostreq);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

     }
 }));

答案 2 :(得分:0)

尝试使用Android的排球。 http://developer.android.com/training/volley/index.html 它为我简化了许多事情。