[英]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.
请参阅第一个代码块,其中我使用php:// input来获取发布的数据。
I'm trying to send a post request from my app to a webserver, and I'm checking for the post vars using PHP: 我正在尝试将发布请求从我的应用发送到Web服务器,并且正在使用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. 该请求始终返回并且为空的json编码数组。
I'm using the latest Android Studio, and the latest OkHttp, com.squareup.okhttp3:okhttp:3.4.1. 我正在使用最新的Android Studio和最新的OkHttp,com.squareup.okhttp3:okhttp:3.4.1。 For me, this is like the "Hello World" of OkHttp in Android Studio.
对我来说,这就像Android Studio中OkHttp的“ Hello World”。
In MainActivity.java: 在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: 我的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. 调试时,我可以看到params [1]值是预期的类似于json的字符串,但这是我最后一次看到它。
I've tried forming the json in a number of ways, so I'm not sure if that's the problem. 我已经尝试过多种方式形成json,所以我不确定这是否是问题。 I just don't understand why I can't see the posted vars when the post request gets to the server.
我只是不明白为什么在发布请求到达服务器时为什么看不到发布的var。
How can I see the posted vars on the webserver? 如何查看网络服务器上发布的var? What am I doing wrong?
我究竟做错了什么? I've only been using Android Studio and Java for less than a week, so I have no clue.
我仅使用Android Studio和Java不到一个星期,所以我一无所知。 I've really looked around the internet a lot for the answer, and so posting here is the last resort.
我真的在互联网上四处寻找答案,因此在此处发布是最后的选择。
Thanks! 谢谢!
事实证明,必须使用php:// input来获取发布的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.