doubairan4213 2016-07-27 02:00
浏览 85

为什么我不从OkHttp3收到POST变量? (Android Studio)

I've answered my own question here. See the first code block where I use php://input to get the posted data.

I'm trying to send a post request from my app to a webserver, and I'm checking for the post vars using PHP:

if( isset( $_POST['name'] ) ){
    echo json_encode(['status' => 1]);
}else if( $posted_data = (string) @file_get_contents('php://input') ) {
    echo json_encode(['status' => 2]);
}else{
    echo json_encode($_POST);
}

The request always returns and empty json encoded array.

I'm using the latest Android Studio, and the latest OkHttp, com.squareup.okhttp3:okhttp:3.4.1. For me, this is like the "Hello World" of OkHttp in Android Studio.

In MainActivity.java:

public void postSomething(View view) {
    String url = "https://example.com/json_api_test.php";
    String json = "{\"name\":\"cholula\"}";
    OkHttpPostHandler handler = new OkHttpPostHandler();
    String result = "";
    try {
        result = handler.execute(url, json).get();
    } catch (Exception e) {
        e.printStackTrace();
    }
    displayPostResponse(result + "
");
}

My OkHttpPostHandler.java:

public class OkHttpPostHandler extends AsyncTask<String, Void, String> {

    OkHttpClient client = new OkHttpClient();

    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    @Override
    protected String doInBackground(String... params) {

        RequestBody body = RequestBody.create(JSON, params[1]);

        Request request = new Request.Builder()
                .url(params[0])
                .post(body)
                .build();

        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        }
        catch( Exception e ){
            return "HTTP Request Error";
        }
    }
}

When I debug, I can see that the params[1] value is the expected json-like string, but that's the last time I see it.

I've tried forming the json in a number of ways, so I'm not sure if that's the problem. I just don't understand why I can't see the posted vars when the post request gets to the server.

How can I see the posted vars on the webserver? What am I doing wrong? I've only been using Android Studio and Java for less than a week, so I have no clue. I've really looked around the internet a lot for the answer, and so posting here is the last resort.

Thanks!

  • 写回答

1条回答 默认 最新

  • dongsui5464 2016-07-27 02:29
    关注

    It turns out that one must use php://input to get the posted data.

    评论

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来