1

I am trying to post JSONObject from android app to php web application using the below code.

String url = "http://10.0.2.2/test/"
URL rest_url = new URL(url);
JSONObject params = new JSONObject();
params.put("username","admin"); 

// Send POST data request
BufferedReader reader=null;

DataOutputStream printout;
URLConnection conn = rest_url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( params.toString());
wr.close();

When I try to retreive the username in php I am getting null value.

 <?php echo $_POST['username'];
 ?>
mahesh
  • 119
  • 10

2 Answers2

5

to avoid writing HTTP code in every class for connection i did this.

created separate http class and have put this code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;


public class HttpConnect
{
    HttpClient httpClient;
    String Url;
    private static final String                 DEBUG_TAG = "TAG";


    public HttpConnect(String url) {
        this.Url = url;
        httpClient = new DefaultHttpClient();
    }

    public HttpEntity Get() throws ClientProtocolException, IOException{

        HttpGet httpGet = new HttpGet(Url);
        HttpResponse httpResponseGet = httpClient.execute(httpGet);
        HttpEntity resEntityGet = httpResponseGet.getEntity();
        return resEntityGet;
    }

    public HttpEntity Post(HashMap<String, String> c) throws ClientProtocolException, IOException{

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(Url);

        // set up post data
        ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
        Iterator<String> it = c.keySet().iterator();
        while (it.hasNext())
        {
            String key = it.next();
            nameValuePair.add(new BasicNameValuePair(key, c.get(key)));
        }

        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
        HttpResponse httpResponseGet = httpClient.execute(httpPost);
        HttpEntity resEntityGet = httpResponseGet.getEntity();
        return resEntityGet;

    }

}

and from your class access this class by posting your key value data in HashMap<String, String> obj = new HashMap<String, String>();

obj.put("username","admin");
HttpEntity resEntityGet = new HttpConnect("URL").Post(obj);

convert resEntityGet entitiy to string by like this

String responseString = EntityUtils.toString(resEntityGet); //response returned from your script
Jolson Da Costa
  • 1,095
  • 1
  • 12
  • 31
  • 1
    It's also a good solution. But as far as I know the apache http client is not supported anymore. – Mauker Sep 13 '15 at 16:43
4

You're not sending a POST request on your Android code. You're just printing a plain String, which in your case is your JSONObject. You'll have to change a few things for it to work.

First of all, set your conn to send a POST.

conn.setRequestMethod("POST");

Then, create a List of NameValuePair. Like the example below.

List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username", params.toString()));

Now use this method I've taken from this answer.

private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {

    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}

And send the data like the code below:

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(pairs));
writer.flush();
writer.close();
os.close();

EDIT: It seems that NameValuePair is deprecated on API 22, check this answer for more details.

Community
  • 1
  • 1
Mauker
  • 11,237
  • 7
  • 58
  • 76