In Retrofit 2 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) {
// ...
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…