chris edwards
chris edwards

Reputation: 1432

Android (Java) HTTP POST JSON to server, but the server tells me no POST variables were seen

A member of my group project at university created this php for our application.

if ( $_SERVER['REQUEST_METHOD'] != 'POST' ) {
  header( 'HTTP/1.0 405 Method Not Allowed' );
  output( 2, 'only POST is accepted; received ' . $_SERVER['REQUEST_METHOD'], true );
}

# catch empty POST requests
if ( count( $_POST ) == 0 ) {
  output( 3,  'no POST variables were sent' );
}

My code passes the first test, but it is always failing this second test. with the error code '3' 'no POST variables were sent'

This is the android code responsible for sending the POST request:

public void uploadToServer(Vector<PointOfInterest> pois)  {

        try {
            JSONObject auth = new JSONObject();
            JSONObject walk = new JSONObject();
            JSONArray points = new JSONArray();




            walk.put("walk name", "TEST NAME");
            walk.put("walk desc short", "TEST SHORT");
            walk.put("walk desc long", "TEST LONG");


            for(int i = 0; i < pois.size(); i ++){

                JSONObject location = new JSONObject();
                location.put("name", pois.get(i).getName());
                location.put("timestamp", 0);
                location.put("lattitude",pois.get(i).getLattitude());
                location.put("longitude",pois.get(i).getLongitude());
                location.put("Description",pois.get(i).getDescription());

                points.put(location);

            }

            auth.put("data", walk);

            walk.put("locations", points);

            auth.put("authorization","");
            auth.put("hash","3b6decebf0bab0e0a08c18a94849d6df1e536d65");
            auth.put("salt", "dave");

            UploadASyncTask upload = new UploadASyncTask();
            upload.execute(auth);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


private class UploadASyncTask extends AsyncTask<JSONObject, Void, Void>{

        @Override
        protected Void doInBackground(JSONObject...auth) {
            try{
                HttpClient httpclient = new DefaultHttpClient();

                HttpPost httpPost = new HttpPost("http://project.chippy.ch/upload.php");

                String json = "";

                json = auth.toString();

                StringEntity se = new StringEntity(json);
                se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                httpPost.setEntity(se);

                httpPost.setHeader("User-Agent", "WalkingTourCreator/1.0");
                httpPost.setHeader("Accept", "application/json");
                httpPost.setHeader("Content-type", "application/json");
                //httpPost.setHeader("data", json);

                HttpResponse httpResponse = httpclient.execute(httpPost);

                InputStream inputStream = httpResponse.getEntity().getContent();
                String result = "";

                if(inputStream != null){
                    result = convertInputStreamToString(inputStream);

                }
                else{
                    result = "Did not work!";

                }

                Log.d("RESULT", result);


            }catch(Exception e){

                Log.e("ERROR IN SEVER UPLOAD", e.getMessage());
            }
            return null;


        }

Any ideas, or any obvious problems?

The guy who made the php said this:

"POST needs key-value pairs (as far as I can tell); you'll need to send a key of "data" with the JSON as the contents."

As far as i am aware aren't i doing this?

I have followed a lot of posts on this site and various other bloggs etc, and they all seem to do a similar thing to what i am doing.

Cheers Chris.

Upvotes: 0

Views: 11751

Answers (3)

chris edwards
chris edwards

Reputation: 1432

Solved:

HttpParams params = new BasicHttpParams();
//params.setParameter("data", auth);
HttpClient httpclient = new DefaultHttpClient(params);

HttpPost httpPost = new HttpPost("http://project.chippy.ch/upload.php");

List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("data", auth.toString()));

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
entity.setContentEncoding(HTTP.UTF_8);
httpPost.setEntity(entity);

was required instead of

HttpClient httpclient = new DefaultHttpClient();

HttpPost httpPost = new HttpPost("http://project.chippy.ch/upload.php");

String json = "";

json = auth.toString();

StringEntity se = new StringEntity(json);
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);

httpPost.setHeader("User-Agent", "WalkingTourCreator/1.0");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");

Upvotes: 3

Tony Maro
Tony Maro

Reputation: 1939

Actually try this answer. It appears that trying to send the auth as an entity string while also attaching a file (i.e. JSON) fails unless you create the auth header properly like so:

how to send http request using http header

Upvotes: 0

Tristan Burnside
Tristan Burnside

Reputation: 2566

Your friend is correct you do need key-value pairs.

StringEntity is just a raw string which is inserted into the http message data field. This must be properly formatted for the receiver to parse it.

Try using URLEncodedFormEntity which you will pass a list (of 1) key value pairs. The key will be whatever you want to call the parameter and the value will be the json string

EXAMPLE:

BasicNameValuePair param = new BasicNameValuePair("paramName",json);
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>()
params.add(param);
URLEncodedFormEntity entity = new URLEncodedFormEntity(params);
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(entity);

Upvotes: 2

Related Questions