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.