本文介绍了HttpURLConnection向Apache / PHP发送JSON POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力使用HttpURLConnection和OutputStreamWriter。

I'm struggling with HttpURLConnection and OutputStreamWriter.

代码实际到达服务器,因为我得到了有效的错误
回复。发出POST请求,但没有收到数据
服务器端。

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

非常感谢任何正确使用此东西的提示。

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

代码在AsyncTask中

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

我想发送的JSON:

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

我应该得到的回复:

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输出:

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}

如果我追加? action = login URL 我可以从服务器获得成功响应。但只有 action 参数注册服务器端。

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:欢迎,请求:登录}

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

嗯,毕竟数据会被转移。

Well, data get transferred after all.

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

Solution offered by @greenaps does the trick:

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

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

PHP script above updated to show the solution.

推荐答案

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

将显示json文本。使用它像:

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

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

这篇关于HttpURLConnection向Apache / PHP发送JSON POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 13:57
查看更多