2016-04-08 31 views
2

我正在尝试使用RetroFit2OkHttp3在PHP脚本上执行POST方法。我一直在做GET方法,但我一直在发布问题。OkHttp POST似乎不发送请求正文

我有一个HttpLoggingInterceptor设置与我的OkHttpClient,它完美记录请求身体。但是我的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接口设置这样的:

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

我得到一组空括号。

回答

1

我在这里找到我的答案: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')); 
}