php - OkHttp POST 似乎没有发送请求正文

标签 php android post retrofit2 okhttp

我正在尝试使用 RetroFit2OkHttp3 在 PHP 脚本上执行 POST 方法。我一直在完美地执行 GET 方法,但我在发布时遇到了问题。

我使用 OkHttpClient 设置了一个 HttpLoggingInterceptor,它完美地记录了请求正文。但是我的 PHP 脚本没有收到数据,所以我尝试在收到数据后立即输出 $_POST 数据,但它是一个空字符串。我无法判断是 Android 端、服务器端还是两者都有问题。

我的 RetroFit 对象和 OkHttpClient 设置如下:

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

OkHttpClient client = new OkHttpClient.Builder()
        .cookieJar(RestCookieJar.getInstance())
        .addInterceptor(interceptor)
        .build();

Gson gson = new GsonBuilder()
        .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
        .registerTypeAdapter(Instant.class, new InstantAdapter())
        .registerTypeAdapter(LatLng.class, new LatLngAdapter())
        .registerTypeAdapter(Uri.class, new UriAdapter())
        .create();

Retrofit retrofit = new Retrofit.Builder()
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create(gson))
        .client(client)
        .baseUrl(BASE_URL)
        .build();

RestService service = retrofit.create(RestService.class);

然后我的RestService接口(interface)是这样设置的:

public interface RestService {

    @GET("api/index.php")
    Call<List<Session>> getSessions();

    @POST("api/index.php")
    Call<ResponseBody> postSession(@Body Session session);
}

正如我提到的,这一切似乎都有效,但是当我调用时:

<?php

    if($_SERVER['REQUEST_METHOD'] === 'POST') {
        print_r($_POST);
    }

我得到一组空的括号。

最佳答案

我在这里找到了答案:php $_POST array empty upon form submission . Retrofit 自动将 Content-Type 设置为 "application/json; charset=UTF-8",在 PHP 5.0 - 5.19 版本中,有一个 bug导致请求主体未被解析为 $_POST 变量。我使用的服务器运行的是 PHP 5.10(我无法控制)。

此错误的解决方法是自己从原始请求正文中解析 JSON 数据:

if($_SERVER['CONTENT_TYPE'] === 'application/json; charset=UTF-8') {
    $_POST = json_decode(file_get_contents('php://input'));
}

关于php - OkHttp POST 似乎没有发送请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36508889/

相关文章:

php - 如何通过 Ant 检索 Composer?

php - 保持 LDAP session

android - 通过 cmd nodejs [windows 7] 的 Phonegap 安装问题

java - Android - 在 ExpandableListView 的每一行中的项目上设置监听器

Android - 在多个 View 上呈现相同的视频

php - AJAX 无法 POST 到 PHP 文件

java - html 到 jsp 电子邮件表单 post - 空参数

PHP base64编码不同的结果

php - 如何检查网站是否正常运行并长期存储结果

php - 如何从 PHP 向通常使用 AJAX 调用访问的服务发送 POST 请求?