24

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!

3
  • Thanks for taking the time to document your issue w/ the 403 response. Had the same thing for a week and your post finally has me moving in the right direction! Commented May 16, 2011 at 1:56
  • @Toran Billups not a problem, I'm glad it has helped you!! Commented Sep 21, 2011 at 23:35
  • Your variables post to your PHP script correctly. How would you pull each variable say "engineer" and "fuel" and insert them into a MySQL database for example. It looks like all you can do is just use the $_POST['vehicle']; variable. Would very much welcome a response to this. Commented Apr 3, 2013 at 11:11

4 Answers 4

11

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?

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

2 Comments

Could you possibly share your PHP file that contains json_decode because I think how my server is decoding the json data (wrongly) may be related to yours.
json_decode(stripslashes($_POST['vehicle']), true); will return php array, json_decode(stripslashes($_POST['vehicle'])); returns php stdclass obj, which is hard to use. +1 for correct answer, thx
4
StringEntity s = new StringEntity(c.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
request.setEntity(s);

Comments

0

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.

1 Comment

Thanks Sergey, but I am using a POST method to send the data, not passing parameters for GET from the PHP script.
0

Try this code it works perfectly

*For HttpClient class* download jar file "httpclient-4.3.6.jar" and put in libs folder then
Compile:   dependencies {compile files('libs/httpclient-4.3.6.jar')}

repositories {
        maven {
            url "https://jitpack.io"
        }
    }

then call HttpClient class this AsyncTask Like this:

private class YourTask extends AsyncTask { private String error_msg = "Server error!";

    private JSONObject response;



    @Override
    protected Boolean doInBackground(String... params) {
        try {
            JSONObject mJsonObject = new JSONObject();
            mJsonObject.put("user_id", "user name");
            mJsonObject.put("password", "123456");
            String URL=" Your Link"

            //Log.e("Send Obj:", mJsonObject.toString());

            response = HttpClient.SendHttpPost(URL, mJsonObject);
            boolean status = response != null && response.getInt("is_error") == 0; // response

            return status;
        } catch (JSONException | NullPointerException e) {
            e.printStackTrace();
            mDialog.dismiss();
            return false;
        }
    }

    @Override
    protected void onPostExecute(Boolean status) {
       // your code

    }
}

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.