Java – Android | Send “POST” JSON Data to Server

androidjava

I used this code to send post data to server using android. Could anyone give me any idea or your sample how to send POST OR GET json data to server TOMCAT..!
Steps tips :

  1. create HttpClient
  2. make POST request to the given URL
  3. build jsonObject
  4. convert JSONObject to JSON to String
  5. set json to StringEntity
  6. set httpPost Entity
  7. Set some headers to inform server about the type of the content
  8. Execute POST request to the given URL
  9. receive response as inputStream
  10. convert inputstream to string
  11. return result

    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
    
            @Override
            protected String doInBackground(String... urls) {
    
            person = new Person();
            person.setName(etName.getText().toString());
            person.setCountry(etCountry.getText().toString());
            person.setTwitter(etTwitter.getText().toString());
    
            return POST(urls[0],person);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
       }
    }
    

Best Answer

You are using HttpClient. Actually Android deprecates HttpClient insted of HttpClient you need to "HttpURLConnection" for POST Request check Here one of the sample : here

Updated:

You need to add following two more line for the sample code for achieve your requirement.

conn.addRequestProperty("Accept", "application/json");
conn.addRequestProperty("Content-Type", "application/json");

In given Sample Code:

conn.setDoOutput(true);
//Add the following line to the given sample
===============> updated for JSON POST <========================= 
conn.addRequestProperty("Accept", "application/json");
conn.addRequestProperty("Content-Type", "application/json");
===============> updated for JSON POST <========================= 
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));
params.add(new BasicNameValuePair("secondParam", paramValue2));
params.add(new BasicNameValuePair("thirdParam", paramValue3));