1

I am trying to build a small application in which the application will communicate with a php script with the help of JSON objects. I successfully implemented the GET Request test application but using JSON with post is creating problems. The code generates no error but my php script reply with no nothing except an empty Array() which implies that nothing was sent over the connection with code:

<?php  print_r($_REQUEST);  ?>

and trying with

<?php  print($_REQUEST['json']); ?>

throws HTML back to the application with json variable not found error.

I have already tried a few solutions mentioned here including: How to send a JSON object over Request with Android? and How to send a json object over httpclient request with android so it would be great if you can point out my mistake and can briefly describe what exactly I was doing wrong. Thanks.

Here is the code snippet for from where the JSON Object is converted into string and then attached to a Post variable.

        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppostreq = new HttpPost(wurl);
        StringEntity se = new StringEntity(jsonobj.toString());
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httppostreq.setEntity(se);
            //httppostreq.setHeader("Accept", "application/json");
        //httppostreq.setHeader("Content-type", "application/json");
        //httppostreq.setHeader("User-Agent", "android");
        HttpResponse httpresponse = httpclient.execute(httppostreq);
        HttpEntity resultentity = httpresponse.getEntity();

Here is TCP Stream Dump collected through wireshark if it can help:

POST /testmysql.php?test=true HTTP/1.1
Content-Length: 130
Content-Type: application/json;charset=UTF-8
Content-Type: application/json;charset=UTF-8
Host: 192.168.100.4
Connection: Keep-Alive
User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)
{"weburl":"hashincludetechnology.com","header":{"devicemodel":"GT-I9100","deviceVersion":"2.3.6","language":"eng"},"key":"value"}HTTP/1.1 200 OK
Date: Mon, 30 Apr 2012 22:43:10 GMT
Server: Apache/2.2.17 (Win32)
Content-Length: 34
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
Array
(
    [test] => true
)
Test // echo statement left intentionally.
Community
  • 1
  • 1
Osama Shabrez
  • 362
  • 3
  • 16
  • Have you tried a packet sniffer to determine if the issue is on the client or server side? – Steve Apr 30 '12 at 22:24
  • @Steve the script is actually sending packets back with Array() and if I append a GET Request at the of the url those variables are returned as well in the Request Array. Only this JSON Object this is creating problem. I am testing this application on my i9100 over lan to my system on which wamp (Apache server) is installed and all other projects are working just fine – Osama Shabrez Apr 30 '12 at 22:31

3 Answers3

1

you are using PHP on the server side, so your HTTP entity must be a multipart encoded one. See this link. You are using a string entity, but this is not correct. It must be a MultipartEntity, which emulates what the browser does when you submit a form in a web page. MultipartEntity should be in httpmime jar.

Once you have your multipart entity, simply add a Part named "json", and set its contents to the string representation of your json-encoded object.

Note that this answer is because you use PHP on the server side, so you must use its "protocol" to read variables via $_REQUEST. If you used your own request parser oh the server side, even a StringEntity could be ok. See HTTP_RAW_POST_DATA

Raffaele
  • 20,627
  • 6
  • 47
  • 86
  • If you can provide an example? Will I have to embed the JSON Object inside the MultipartEntity? Any help would be great. – Osama Shabrez Apr 30 '12 at 22:46
  • I updated my answer. Anyway, you should create a multipart entity and add a part named "json", with contents from json.toString() – Raffaele Apr 30 '12 at 22:50
  • $HTTP_RAW_POST_DATA worked like a magic, I'll prefer to build my own parser around the raw post data. Thanks a lot. – Osama Shabrez Apr 30 '12 at 23:04
1

The below should work. Make sure to set the appropriate keys for what your form post is expecting at the top. Also I included how to send an image as well as other various json data, just delete those lines if that is not necessary.

static private String postToServerHelper(
            String action,
            JSONObject jsonData,
            byte[] imageData){

        // keys for sending to server
        /** The key for the data to post to server */
        final String KEY_DATA = "data";
        /** The key for the action to take on server */
        final String KEY_ACTION = "action";
        /** The return code for a successful sync with server */
        final int GOOD_RETURN_CODE = 200;
        /** The key for posting the image data */
        final String KEY_IMAGE = "imageData";
        /** The image type */
        final String FILE_TYPE = "image/jpeg";
        /** The encoding type of form data */
        final Charset ENCODING_TYPE = Charset.forName("UTF-8");

        // the file "name"
        String fileName = "yourFileNameHere";

        // initialize result string
        String result = "";

        // initialize http client and post to correct page
        HttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://www.yourdomain.com/yourpage.php");

        // set to not open tcp connection
        httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

        // build the values to post, the action and the form data, and file data (if any)
        MultipartEntity multipartEntity = new MultipartEntity(
                HttpMultipartMode.BROWSER_COMPATIBLE);
        try{
            multipartEntity.addPart(KEY_ACTION, new StringBody(action, ENCODING_TYPE));
            multipartEntity.addPart(KEY_DATA, new StringBody(jsonData.toString(), ENCODING_TYPE));
            if (imageData != null){
                multipartEntity.addPart(KEY_IMAGE, new ByteArrayBody(imageData, FILE_TYPE, fileName));
            }
        }catch (Exception e){
            return e.getMessage();
        }

        // set the values to the post
        httpPost.setEntity(multipartEntity);

        int statusCode= -1;

        // send post
        try {
            // actual send
            HttpResponse response = client.execute(httpPost);

            // check what kind of return
            StatusLine statusLine = response.getStatusLine();
            statusCode = statusLine.getStatusCode();

            // good return
            if (statusCode == GOOD_RETURN_CODE) {
                // read return
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                        builder.append(line + "\n");
                }
                content.close();
                result = builder.toString();

                // bad return   
            } else {
                return String.parse(statusCode);
            }

            // different failures   
        } catch (ClientProtocolException e) {
            return e.getMessage();
        } catch (IOException e) {
            return e.getMessage();
        }

        // return the result
        return result;  
    }
Kyle
  • 611
  • 4
  • 6
  • Raffaele's answer solved my problem, still I am highly grateful that you took time to answer with a code example, unfortunately I am not unable to vote up, but still I am glad that you tried to help :) – Osama Shabrez Apr 30 '12 at 23:08
0

DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url);

            JSONObject clientList = new JSONObject ();
            clientList.put("name","");
            clientList.put("email","");
            clientList.put("status","");
            clientList.put("page","");



            JSONObject listclient = new JSONObject ();
            listclient.put("mydetail", clientList);

   //--List nameValuePairs = new ArrayList(1);
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("token", tokenid));
            nameValuePairs.add(new BasicNameValuePair("json_data", listclient.toString()));


            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            Log.d("JSON",nameValuePairs.toString());

            //-- Storing Response
            HttpResponse httpResponse = httpClient.execute(httpPost);
Manoj Pal
  • 170
  • 1
  • 1
  • 11