Reputation: 15135
I am trying to use RetroFit2
and OkHttp3
to do a POST method on a PHP script. I have been doing GET methods perfectly fine, but I have been having problems with posting.
I have an HttpLoggingInterceptor
set up with my OkHttpClient
, and it logs the request body perfectly. But my PHP script was not receiving the data, so I tried just outputting the $_POST
data as soon as I got it, but it is an empty string. I cannot tell if there is something wrong on the Android side, the server side, or both.
My RetroFit
object and OkHttpClient
are set up like so:
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);
Then my RestService
interface is set up like this:
public interface RestService {
@GET("api/index.php")
Call<List<Session>> getSessions();
@POST("api/index.php")
Call<ResponseBody> postSession(@Body Session session);
}
As I mentioned, this all seems to work, but when I call:
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
print_r($_POST);
}
I get an empty set of parenthesis.
Upvotes: 3
Views: 1709
Reputation: 15135
I found my answer here: php $_POST array empty upon form submission. Retrofit automatically sets the Content-Type
to "application/json; charset=UTF-8"
, which in PHP versions 5.0 - 5.19, there is a bug causing the request body to not be parsed into the $_POST
variable. The server I am using is running PHP 5.10 (which I have no control over).
The workaround for this bug is to parse the JSON data yourself from the raw request body:
if($_SERVER['CONTENT_TYPE'] === 'application/json; charset=UTF-8') {
$_POST = json_decode(file_get_contents('php://input'));
}
Upvotes: 4