Question

I'm new in android I try to send POST method to PHP using JSON the data I sent do not appear in PHP, In PHP the request released but when I try to read the POST data I have array null.

protected void sendJson(final String username, final String password) {
        Thread t = new Thread() {

            public void run() {
                Looper.prepare();
                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); 
                HttpResponse response;
                JSONObject json = new JSONObject();
                String URL = "MY_URL";

                try {
                        HttpPost post = new HttpPost(URL);
                        json.put("section", "API");
                        json.put("username", username);
                        json.put("password", password);
                        StringEntity se = new StringEntity( json.toString());  
                        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                        post.setEntity(se);
                        response = client.execute(post);

                        if(response!=null)
                        {
                            String result = EntityUtils.toString(response.getEntity());

                            Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
                            //InputStream in = response.getEntity().getContent(); //Get the data in the entity
                        }

                } catch(Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getBaseContext(), "Cannot Estabilish Connection", Toast.LENGTH_LONG).show();
                }    
                Looper.loop();
            }
        };    
        t.start();      
    } 
Was it helpful?

Solution

Try accumulate in place of put :

 json.accumulate("section", "API");
                    json.accumulate("username", username);
                    json.accumulate("password", password);

Try this methode to set the header:

post.setEntity(se);

post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");

Take also a look to Gson API if you want also. It helps to parse ... this IS a nice tuto .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top