Home » Android » java – HttpURLConnection sending JSON POST request to Apache/PHP

java – HttpURLConnection sending JSON POST request to Apache/PHP

Posted by: admin June 16, 2020 Leave a comment

Questions:

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.

How to&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);

Answer:

try to use DataOutputStream instead of OutputStreamWriter.

        DataOutputStream out = new DataOutputStream(_conn.getOutputStream());
        out.writeBytes(your json serialized string);
        out.close();

Answer:

I’ve made server tell me what it got from me.

Request Headers and POST Body

<?php
    $requestHeaders = apache_request_headers();
    print_r($requestHeaders);

    print_r("\n -= POST Body =- \n");

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

Works like a charm)

Answer:

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.

got this same situation, and come to @greenapps answer.
you should know what server recieved from ‘post request’

what i do first on the server side :

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

then print/Toast/show message response on the client side. make sure its correct form, like :

{"username": "yourusername", "password" : "yourpassword"}

if the response like this (because you post the request with yourHashMap.toString()) :

{username=yourusername,password=yourpassword}

instead using .toString(), use this method instead to turn HashMap into String :

private String getPostDataString(HashMap<String, String> postDataParams) {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String,String> entry :   postDataParams.entrySet()){
            if(first){
                first = false;
            }else{
                result.append(",");
            }
            result.append("\"");
            result.append(entry.getKey());
            result.append("\":\"");
            result.append(entry.getValue());
            result.append("\"");
        }
        return "{" + result.toString() + "}";
    }