0

I'm trying to submit some data formatted as a JSONObject to a web server. My understanding was that this is done with an httpclient on android and then a php file on the server. If that's not the case stop here and correct me, otherwise here's how i'm trying to send the data:

HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://myhost/data.php");
            try {
                String UN = username.getText().toString();
                String PW = password.getText().toString();
                String jString = "{\"login\": { \"username\": \""+UN + "\",\"password\": \""+PW+"\"}}";
                JSONDATA = new JSONObject(jString);
                //JSONDATA = new JSONObject();
                //JSONDATA.put("username", UN);
                //JSONDATA.put("password", PW);

should i be using: httppost.setEntity(new UrlEncodedFormEntity(JSONDATA));

or should i be doing it like so:

                StringEntity se = new StringEntity(JSONDATA.toString());  
                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                HttpEntity entity;
                entity = se;
                httppost.setEntity(entity);
                HttpResponse response;
                response = httpclient.execute(httppost);
0

1 Answer 1

3

The question really is how are you planning to pull the data out on the server? What does your PHP look like? What may be easiest is to just pass the JSON as a parameter:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myhost/data.php");
try {
   String UN = username.getText().toString();
   String PW = password.getText().toString();
   String jString = "{\"login\": { \"username\": \""+UN + "\",\"password\":\""+PW+"\"}}";
   List <NameValuePair> nvps = new ArrayList <NameValuePair>();
   nvps.add(new BasicNameValuePair("value", jString));
   httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));                 

   HttpResponse response;
   response = httpclient.execute(httppost);

and then on the server side you can just do

<?php
   $obj = json_decode($_POST['value']);

to retrieve it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.