小编典典

HttpURLConnection将JSON POST请求发送到Apache / PHP

ajax

我在HttpURLConnection和OutputStreamWriter方面挣扎。

代码实际上到达了服务器,因为我确实收到了有效的错误响应。发出了POST请求,但服务器端未收到任何数据。

正确使用此东西的任何提示均受到高度赞赏。

该代码在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;                                                                    
}

我正在尝试发送的JSON:

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

我从服务器得到的响应:

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

我应该得到的回应是:

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

服务器端PHP脚本:

<?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;


?>

以及Android Studio中的logcat输出:

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}

如果附加?action=login到,则URL可以从服务器获得成功响应。但是只有 动作 参数在服务器端注册。

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

结论必须是没有数据通过 URLConnection.write(output.getBytes("UTF-8"));

好吧,数据毕竟会被传输。

@greenaps提供的解决方案可以解决问题:

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

上面的PHP脚本已更新以显示解决方案。


阅读 381

收藏
2020-07-26

共1个答案

小编典典

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

将向您显示json文本。像这样工作:

$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
2020-07-26