1

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();
       }
    }
    
Darshan Lila
  • 5,772
  • 2
  • 24
  • 34

3 Answers3

3

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));
Community
  • 1
  • 1
Ravi Jaggarapu
  • 627
  • 3
  • 10
  • of cource my friend but i use json to post or get data from the server.any other sample? –  Jan 01 '16 at 10:37
1

If you need to get data try this...

try{
    URL url = new URL("http://www.youraddresheredude.com/andthefile");
    //Open the connection here, and remember to close it when job its done.
    URLConnection conn = url.openConnection();
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    conn.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    //theJSONYouWantToSend should be the JSONObject as String
    wr.write(convertStandardJSONString(theJSONYouWantToSend));  //<--- sending data.

    wr.flush();

    //  Here you read any answer from server.
    BufferedReader serverAnswer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = serverAnswer.readLine()) != null) {

        System.out.println("LINE: " + line); //<--If any response from server
        //use it as you need, if server send something back you will get it here.
    }

    wr.close();
    serverAnswer.close();

} catch (Exception e) {
    Log.e("Cuack", "Something its wrong");
}
Elennio
  • 46
  • 5
  • You should really add some explanation as to why this code should work - you can also add comments in the code itself - in its current form, it does not provide any explanation which can help the rest of the community to understand what you did to solve/answer the question. – ishmaelMakitla Aug 01 '16 at 20:00
  • The question asks how to SEND data to the server not get data back from the server. – JesseBoyd Feb 27 '17 at 06:08
  • you would like to know if the data its on the server. – Elennio Mar 01 '17 at 02:03
-2
public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static String responseString;

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public static JSONObject makeHttpRequest(String url, String method,
                                         List<NameValuePair> params) {

    // Making HTTP request
    Log.d("json class", url + "," + method + "," + params.toString());
    try {

        // check for request method
        if (method == "POST") {
            // request method is POST
            // defaultHttpClient
            Log.d("json class", "post method");
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            Log.d("json class", "HttpPost" + httpPost);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            Log.d("json class", "setentity");
            HttpResponse httpResponse = httpClient.execute(httpPost);

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int responce_code = httpResponse.getStatusLine()
                    .getStatusCode();
            Log.d("responce code", "response method");
            Log.d("responce code", "" + responce_code);
            StatusLine statusLine = httpResponse.getStatusLine();

            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                Log.i("RESPONSE", "6");
                /*
                 * httpResponse.getEntity().writeTo(out); out.close();
                 * String responseString = out.toString(); Log.i("RESPONSE",
                 * ""+responseString);
                 */
                // ..more logic
            } else {
                Log.d("RESPONSE", "null pointer exception");
                // Closes the connection.
                httpResponse.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }

            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } else if (method == "GET") {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            Log.i("url", url);
            HttpGet httpGet = new HttpGet(url);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int responce_code = httpResponse.getStatusLine()
                    .getStatusCode();
            Log.d("responce code", "response method");
            Log.d("responce code", "" + responce_code);

            StatusLine statusLine = httpResponse.getStatusLine();

            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {

                Log.d("RESPONSE", "6");
                httpResponse.getEntity().writeTo(out);
                Log.d("RESPONSE", "7");
                out.close();
                Log.d("RESPONSE", "8");
                responseString = out.toString();
                Log.d("RESPONSE", "9");
                Log.i("RESPONSE", "" + responseString);
                // ..more logic
            } else {
                Log.d("RESPONSE", "null pointer exception");
                // Closes the connection.
                httpResponse.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
            /*
             * HttpEntity httpEntity = httpResponse.getEntity(); is =
             * httpEntity.getContent();
             */
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        /*
         * BufferedReader reader = new BufferedReader(new InputStreamReader(
         * is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder();
         * String line = null; while ((line = reader.readLine()) != null) {
         * sb.append(line + "\n"); } is.close();
         */
        json = responseString.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {

        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // return JSON String
    return jObj;
}

}
Ori Dar
  • 18,687
  • 5
  • 58
  • 72
thirua
  • 1