简体   繁体   中英

Why don't I receive POST vars from OkHttp3? (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 + "\n");
}

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!

事实证明,必须使用php:// input来获取发布的数据。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM