HttpURLConnection sending JSON POST request to Apache/PHP

风格不统一 提交于 2019-11-30 09:34:58
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);

try to use DataOutputStream instead of OutputStreamWriter.

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

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)

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() + "}";
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!