Fernando
Fernando

Reputation: 459

Send a string on Android with HttpPost without using nameValuePairs

I was looking information about how I can send information using HttpPost method on android, and I always see this:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(posturl);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Name","Var1"));
params.add(new BasicNameValuePair("Name2","Var2"));

httppost.setEntity(new UrlEncodedFormEntity(params));    
HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();

The problem is that I cant do that, because I have to connect to a resource that receive a String with XML format.

Any idea about how can I send only the String without using a List<nameValuePair>

Upvotes: 6

Views: 13160

Answers (3)

Rakesh
Rakesh

Reputation: 2770

// Sending HTTPs Requet to Server

    try {
        Log.v("GG", "Sending sever 1 - try");
        // start - line is for sever connection/communication
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "10.0.0.1/abc.php");

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("qrcode", contents));


        httppost.setEntity(new UrlEncodedFormEntity(
                nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        // end - line is for sever connection/communication
        InputStream is = entity.getContent();

        Toast.makeText(getApplicationContext(),
                "Send to server and inserted into mysql Successfully", Toast.LENGTH_LONG)
                .show();

        // Execute HTTP Post Request
        response= httpclient.execute(httppost);

        entity = response.getEntity();
        String getResult = EntityUtils.toString(entity);
        Log.e("response =", " " + getResult);



    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection "
                + e.toString());
    }

Upvotes: -1

Parijat Bose
Parijat Bose

Reputation: 390

You can use JSON as post parameter. Try referring FlexJson

Upvotes: 0

Praful Bhatnagar
Praful Bhatnagar

Reputation: 7435

Have you tried using StringEntity? Above code can be updated to use StringEntity, Following is the resulting code:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(posturl);


httppost.setEntity(new StringEntity("your string"));    
HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();

Upvotes: 19

Related Questions