简体   繁体   中英

Android Http Request POST JSON

I am trying to create a function to make a request, but it is giving some error, I already put permission to the internet, but still

This is my code:

public String request(String Url,JSONObject Data){
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(Url);
        InputStream inputstream;
        String content = "";


            try {

                httppost.setEntity(new StringEntity(Data.toString()));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
          while(true){
              if(entity != null){
                  inputstream =   entity.getContent();
                  content = inputstream.toString();
                  break;
              }
          }

        } catch (Exception ex) {
            return ex.toString();
        } 

        return content;
}

Input:

JSONObject data = new JSONObject();
data.put("teste","teste");
String response = request('urlExample',data);
Toast.makeText(getApplicationContext(),response,Toast.LENGTH_SHORT).show();

Output:

android.os.NetworkOnMainThreadExecption

Network operation does not be launched on Main Thread. You can create another Thread for running it.

Thread thread = new Thread(new Runnable(){ 
     @Override public void run(){ 
         // Run request here !!!!
      } 
    });
thread.start();

I suggest you to use AsyncTask as I mentioned in the comment :

private class LongOperation extends AsyncTask<Void, Void, String> {

        private String mUrl;
        private JSONObject mData;

        public LongOperation(String url, JSONObject data) {
           mUrl = url;
           mData = data;
        }

        @Override
        protected String doInBackground(Void... params) {
            return request(mUrl, mData);
        }

        @Override
        protected void onPostExecute(String response) {
           Toast.makeText(getApplicationContext(),response,
              Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
}

You can start your AsyncTask as follow:

JSONObject data = new JSONObject();
data.put("teste","teste");
new LongOperation('urlExample', data).execute();

I recomend you to use **Volley** , it's a side client library which helps you with the Http-Request.

Search for StringRequest .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM