Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpURLConnection sending JSON POST request to Apache/PHP

I'm struggling with HttpURLConnection and OutputStreamWriter.

The code actually reaches the server, as I do get a valid error response back. A POST request is made, but no data is received server-side.

Any hints to proper usage of this thingy is highly appreciated.

The code is in an AsyncTask

protected JSONObject doInBackground(Void... params) {                                   
    try {                                                                               
        url = new URL(destination);                                                     
        client = (HttpURLConnection) url.openConnection();                              
        client.setDoOutput(true);                                                       
        client.setDoInput(true);                                                        
        client.setRequestProperty("Content-Type", "application/json; charset=UTF-8");   
        client.setRequestMethod("POST");                                                
        //client.setFixedLengthStreamingMode(request.toString().getBytes("UTF-8").length);
        client.connect();                                                               

        Log.d("doInBackground(Request)", request.toString());                           

        OutputStreamWriter writer = new OutputStreamWriter(client.getOutputStream());   
        String output = request.toString();                                             
        writer.write(output);                                                           
        writer.flush();                                                                 
        writer.close();                                                                 

        InputStream input = client.getInputStream();                                    
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));       
        StringBuilder result = new StringBuilder();                                     
        String line;                                                                    

        while ((line = reader.readLine()) != null) {                                    
            result.append(line);                                                        
        }                                                                               
        Log.d("doInBackground(Resp)", result.toString());                               
        response = new JSONObject(result.toString());                                   
    } catch (JSONException e){                                                          
        this.e = e;                                                                     
    } catch (IOException e) {                                                           
        this.e = e;                                                                     
    } finally {                                                                         
        client.disconnect();                                                            
    }                                                                                   

    return response;                                                                    
}                                                                                       

The JSON I'm trying to send:

JSONObject request = {
    "action":"login",
    "user":"mogens",
    "auth":"b96f704fbe702f5b11a31524bfe5f136efea8bf7",
    "location":{
        "accuracy":25,
        "provider":"network",
        "longitude":120.254944,
        "latitude":14.847808
        }
    };

And the response I get from the server:

JSONObject response = {
    "success":false,
    "response":"Unknown or Missing action.",
    "request":null
    };

And the response I should have had:

JSONObject response = {
    "success":true,
    "response":"Welcome Mogens Burapa",
    "request":"login"
    };

The server-side PHP script:

<?php

    $json = file_get_contents('php://input');
    $request = json_decode($json, true);

    error_log("JSON: $json");

    error_log('DEBUG request.php: ' . implode(', ',$request));
    error_log("============ JSON Array ===============");
    foreach ($request as $key => $val) {
        error_log("$key => $val");
    }

    switch($request['action'])
    {
        case "register":

            break;
        case "login":
            $response = array(
                            'success' => true,
                            'message' => 'Welcome ' . $request['user'],
                            'request' => $request['action']
                        );
            break;
        case "location":

            break;
        case "nearby":

            break;
        default:
            $response = array(
                            'success' => false,
                            'response' => 'Unknown or Missing action.',
                            'request' => $request['action']
                        );
            break;
    }

    echo json_encode($response);

    exit;


?>

And the logcat output in Android Studio:

D/doInBackground(Request)﹕ {"action":"login","location":{"accuracy":25,"provider":"network","longitude":120.254944,"latitude":14.847808},"user":"mogens","auth":"b96f704fbe702f5b11a31524bfe5f136efea8bf7"}
D/doInBackground(Resp)﹕ {"success":false,"response":"Unknown or Missing action.","request":null}

If I append ?action=login to the URL I can get a success response from the server. But only the action parameter registers server-side.

{"success":true,"message":"Welcome ","request":"login"}

The conclusion must be that no data is transferred by URLConnection.write(output.getBytes("UTF-8"));

Well, data get transferred after all.

Solution offered by @greenaps does the trick:

$json = file_get_contents('php://input');
$request = json_decode($json, true);

PHP script above updated to show the solution.

like image 445
Mogens TrasherDK Avatar asked Apr 16 '15 16:04

Mogens TrasherDK


2 Answers

echo (file_get_contents('php://input'));

Will show you the json text. Work with it like:

$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
like image 92
greenapps Avatar answered Oct 16 '22 07:10

greenapps


try to use DataOutputStream instead of OutputStreamWriter.

        DataOutputStream out = new DataOutputStream(_conn.getOutputStream());
        out.writeBytes(your json serialized string);
        out.close();
like image 30
Sri777 Avatar answered Oct 16 '22 07:10

Sri777