Skip to main content

Android JSON HttpClient to send data to PHP server with HttpResponse



I am currently trying to send some data from and Android application to a php server (both are controlled by me).





There is alot of data collected on a form in the app, this is written to the database. This all works.





In my main code, firstly I create a JSONObject (I have cut it down here for this example):







JSONObject j = new JSONObject();

j.put("engineer", "me");

j.put("date", "today");

j.put("fuel", "full");

j.put("car", "mine");

j.put("distance", "miles");







Next I pass the object over for sending, and receive the response:







String url = "http://www.server.com/thisfile.php";

HttpResponse re = HTTPPoster.doPost(url, j);

String temp = EntityUtils.toString(re.getEntity());

if (temp.compareTo("SUCCESS")==0)

{

Toast.makeText(this, "Sending complete!", Toast.LENGTH_LONG).show();

}







The HTTPPoster class:







public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException

{

HttpClient httpclient = new DefaultHttpClient();

HttpPost request = new HttpPost(url);

HttpEntity entity;

StringEntity s = new StringEntity(c.toString());

s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

entity = s;

request.setEntity(entity);

HttpResponse response;

response = httpclient.execute(request);

return response;

}







This gets a response, but the server is returning a 403 - Forbidden response.





I have tried changing the doPost function a little (this is actually a little better, as I said I have alot to send, basically 3 of the same form with different data - so I create 3 JSONObjects, one for each form entry - the entries come from the DB instead of the static example I am using).





Firstly I changed the call over a bit:







String url = "http://www.myserver.com/ServiceMatalan.php";

Map<String, String> kvPairs = new HashMap<String, String>();

kvPairs.put("vehicle", j.toString());

// Normally I would pass two more JSONObjects.....

HttpResponse re = HTTPPoster.doPost(url, kvPairs);

String temp = EntityUtils.toString(re.getEntity());

if (temp.compareTo("SUCCESS")==0)

{

Toast.makeText(this, "Sending complete!", Toast.LENGTH_LONG).show();

}







Ok so the changes to the doPost function:







public static HttpResponse doPost(String url, Map<String, String> kvPairs) throws ClientProtocolException, IOException

{

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost(url);

if (kvPairs != null && kvPairs.isEmpty() == false)

{

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(kvPairs.size());

String k, v;

Iterator<String> itKeys = kvPairs.keySet().iterator();

while (itKeys.hasNext())

{

k = itKeys.next();

v = kvPairs.get(k);

nameValuePairs.add(new BasicNameValuePair(k, v));

}

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

}

HttpResponse response;

response = httpclient.execute(httppost);

return response;

}







Ok So this returns a response 200







int statusCode = re.getStatusLine().getStatusCode();







However the data received on the server cannot be parsed to a JSON string. It is badly formatted I think (this is the first time I have used JSON):





If in the php file I do an echo on $_POST['vehicle'] I get the following:







{\"date\":\"today\",\"engineer\":\"me\"}







Can anyone tell me where I am going wrong, or if there is a better way to achieve what I am trying to do? Hopefully the above makes sense!



Source: Tips4all

Comments

  1. After lots of reading and searching I have found the problem to be with, I beleive magic_quotes_gpc being enabled on the server.

    Thus, using:

    json_decode(stripslashes($_POST['vehicle']));


    In my example above removes the slashes and allows the JSON to be decoded properly.

    Still not sure why sending a StringEntity causes a 403 error?

    ReplyDelete
  2. StringEntity s = new StringEntity(c.toString());
    s.setContentEncoding("UTF-8");
    s.setContentType("application/json");
    request.setEntity(s);

    ReplyDelete
  3. Change

    (String url = "http://www.server.com/MainPage.php";)


    to

    (String url = "http://www.server.com/MainPage.php?";)


    Question mark at the end is necessary when you're trying to send parameters to php script.

    ReplyDelete
  4. Try this code it works for me

    public void postData(String result,JSONObject obj) {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
    HttpConnectionParams.setSoTimeout(myParams, 10000);

    String json=obj.toString();

    try {

    HttpPost httppost = new HttpPost(result.toString());
    httppost.setHeader("Content-type", "application/json");

    StringEntity se = new StringEntity(obj.toString());
    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    httppost.setEntity(se);

    HttpResponse response = httpclient.execute(httppost);
    String temp = EntityUtils.toString(response.getEntity());
    Log.i("tag", temp);


    } catch (ClientProtocolException e) {

    } catch (IOException e) {
    }


    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.