I am looking for some way to post request with raw body with new Retrofit 2.0b1. Something like this:
@POST(\"/token\")
Observable getT
In Retrofit 2.0.0-beta2 you can use RequestBody and ResponseBody to post a body to server using String data and read from server's response body as String.
First you need to declare a method in your RetrofitService:
interface RetrofitService {
@POST("path")
Call<ResponseBody> update(@Body RequestBody requestBody);
}
Next you need to create a RequestBody and Call object:
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://somedomain.com").build();
RetrofitService retrofitService = retrofit.create(RetrofitService.class);
String strRequestBody = "body";
RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"),strRequestBody);
Call<ResponseBody> call = retrofitService.update(requestBody);
And finally make a request and read response body as String:
try {
Response<ResponseBody> response = call.execute();
if (response.isSuccess()) {
String strResponseBody = response.body().string();
}
} catch (IOException e) {
// ...
}
You should be registering a converter for your Type when you are building your Retrofit using addConverter(type, converter).
Converter<T> in 2.0 uses similar approach using old Converter in 1.x version.
Your StringConverter should be something like this:
public class StringConverter implements Converter<Object>{
@Override
public String fromBody(ResponseBody body) throws IOException {
return ByteString.read(body.byteStream(), (int) body.contentLength()).utf8();
}
@Override
public RequestBody toBody(Object value) {
return RequestBody.create(MediaType.parse("text/plain"), value.toString());
}
}
Notes:
ByteString is from Okio library. Charset in your MediaType