0

I am trying to send a JSON post array to a PHP server. The array contains separate objects/tickets that PHP will decode. Android loads the data into the JSON object from its local database just fine. I can log the data it's pulling and see it before it's sent to the PHP server. On the server side the data doesn't make it. It's sending an empty array.

My code:

public void sendQueuedTickets() {
    // Check queue for tickets.
    if (dbc.checkQueTickets() != null) {
        String[] userInfo;
        Cursor cursor = dbc.checkQueTickets();
        int columns = cursor.getColumnCount();
        int rows = cursor.getCount();
        final ArrayList<Integer> queueIDs = new ArrayList<>();
        JSONArray arr = new JSONArray();
        cursor.moveToFirst();
        // Get user info.
        userInfo = dbc.checkCredentials();
        // Add user info and request type to params so server knows what we're doing.
        JSONObject jobj = new JSONObject();
        try {
            jobj.put("username", userInfo[0]);
            jobj.put("serverUserID", userInfo[2]);
            jobj.put("request", "submitTicket");
        } catch (JSONException e) { e.printStackTrace(); }
        // Add SQL tickets to params to be sent.
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < columns; c++) {
                try {
                    jobj.put(cursor.getColumnName(c), cursor.getString(c));
                } catch (JSONException e) { e.printStackTrace(); }
            }
            arr.put(jobj);
            queueIDs.add(cursor.getInt(0)); // id column value.
            cursor.moveToNext();
        }
        // Send ticket(s) to remote server.
        // Set timeout parameters.
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);
        // Continue with http request.
        HttpClient client = new DefaultHttpClient(httpParameters);
        HttpContext httpContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost("http://" + userInfo[3] + "." + dbc.REMOTE_SERVER_URL);
        try {
            StringEntity se = new StringEntity(arr.toString());
            httpPost.setEntity(se);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            HttpResponse response = client.execute(httpPost, httpContext);
            String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
            System.out.println(resFromServer);
            // Delete queued ticket(s) if sent transaction successful.
            if (resFromServer.contains("successfulSubmit")) {
                for (int r = 0; r < rows; r++) {
                    dbc.deleteQueTicket(queueIDs.get(r));
                }
            }
        } catch (Exception e) { e.printStackTrace(); }
    }
}
3
  • Can we see how you are capturing the sent data on the server side? Commented Jul 14, 2015 at 19:04
  • halfer, I managed to lose the original code I was using. I do know I was looking to see if $_POST['json'] was set which wouldn't work. Commented Jul 15, 2015 at 18:21
  • @ChrisC. where is your server side code Commented Jul 15, 2015 at 18:23

2 Answers 2

2

This is the code I use in the PHP server side to get JSON data from Android:

$json = file_get_contents('php://input');
$obj = json_decode($json,true);//true means convert to 2d array

And this the code I use for sending from Android:

private void sendHttp(JSONArray json) throws JSONException, IOException

{
    HttpParams httpParams = new BasicHttpParams();

    HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
    HttpConnectionParams.setSoTimeout(httpParams, 10000);

    HttpClient client = new DefaultHttpClient(httpParams);

    String url = "your url write it here";
    Log.i("","http post on url");
    HttpPost request = new HttpPost(url);//send an httppost to the string url as json format

    request.setEntity(new ByteArrayEntity(json.toString().getBytes(
            "UTF8")));

    request.setHeader("json", json.toString());
    request.setHeader("Accept", "application/json"); 
    request.setHeader("Content-Type", "application/json");
    Log.i("", "excuting request");
    HttpResponse response =client.execute(request);//getting response

    //getting the response
    HttpEntity entity = response.getEntity();
        InputStream is = null;
        StringBuilder sb=null;
        is=entity.getContent();
        BufferedReader reader = new BufferedReader(new       InputStreamReader(is,"iso-8859-1"),10);
        sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");
        String line="0";

        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        is.close();

        String result=sb.toString();
        JSONArray res=new JSONArray(result);//the response json array 

}

The code works 100%.

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

1 Comment

Good answer! Just so you know, we like answers to be as readable as possible here, so if you can use your Shift key every now and again, it does help :-). If you are posting from a mobile phone, the general opinion here is that it's not an ideal device to be posting from.
0

I ended up finding a solution from here that's working. Below is the final code:

public void sendQueuedTickets() {
    // Check queue for tickets.
    if (dbc.checkQueTickets() != null) {
        String[] userInfo;
        Cursor cursor = dbc.checkQueTickets();
        int columns = cursor.getColumnCount();
        int rows = cursor.getCount();
        final ArrayList<Integer> queueIDs = new ArrayList<>();
        JSONArray arr = new JSONArray();
        JSONObject jobj = new JSONObject();
        cursor.moveToFirst();
        // Get user info.
        userInfo = dbc.checkCredentials();
        // Add user info and request type to params so server knows what we're doing.
        try {
            jobj.put("username", userInfo[0]);
            jobj.put("serverUserID", userInfo[2]);
            jobj.put("request", "submitTicket");
        } catch (JSONException e) { e.printStackTrace(); }
        // Add SQL tickets to params to be sent.
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < columns; c++) {
                try {
                    jobj.put(cursor.getColumnName(c), cursor.getString(c));
                } catch (JSONException e) { e.printStackTrace(); }
            }
            arr.put(jobj);
            queueIDs.add(cursor.getInt(0)); // id column value.
            cursor.moveToNext();
        }

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);
        HttpClient client = new DefaultHttpClient(httpParameters);
        HttpPost httpPost = new HttpPost("http://" + userInfo[3] + "." + dbc.REMOTE_SERVER_URL);
        httpPost.setHeader("json",arr.toString());
        httpPost.getParams().setParameter("jsonpost",arr);

        try {
            HttpResponse response = client.execute(httpPost);
            String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
            System.out.println(resFromServer);
            // Delete queued ticket(s) if sent transaction successful.
            if (resFromServer.contains("successfulSubmit")) {
                for (int r = 0; r < rows; r++) {
                    dbc.deleteQueTicket(queueIDs.get(r));
                }
            }
        } catch (Exception e) { e.printStackTrace(); }
    }
}

The PHP server side code is:

if (isset($_SERVER['HTTP_JSON']) {
    $json = $_SERVER['HTTP_JSON'];
    $data = json_decode($json, true);
    print_r($data);
}

This will print out the array of JSON tickets as an associative array.

3 Comments

The PHP does not look correct. The server-side variable HTTP_JSON isn't a thing, as far as I know, so I don't know where that comes from. You either want to grab a particular $_POST['x'] value, or get the raw data from file_get_contents("php://input").
I agree, halfer, but it works. I've had a lot of trouble finding more information on the HTTP_JSON. I've always been under the impression to retrieve information from a sender you should use a $_POST request.
Hmm, strange. It's not documented, but if it works, it works. Does the php://input approach not work for you? I imagine that would be more resilient to server changes.

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.