1
我可以通過retrofit2和okhttp3庫與服務器通信,我獲得以下成功改造2的通信服務器,但身體是空
D/LT: Response successful.
Code: 200
Server: Apache-Coyote/1.1
Content-Type: text/plain;charset=UTF-8
Content-Length: 441
Date: Tue, 14 Jun 2016 08:01:23 GMT
D/LT: responseBody = null
正如你所看到的,我得到一個成功的響應,它是441個字符長。
那麼,爲什麼我會得到一個空身體?
這些都是我的消息來源
MyService client = MyServiceGenerator.createService(MyService.class);
String contentType = "application/json";
String bodyContent = "{'userId': 'user', 'password': 'pwd', 'deviceId': '123', 'applicationId': '123'}";
RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), bodyContent);
Call call = client.session(contentType, requestBody);
// Asynchronic way
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.d("LT","Reached!");
if (response.isSuccessful()) {
Log.d("LT", "Response successful. Code: "+ response.code() + " " + response.headers());
Void decodedResponseBody = (Void)response.body();
if (decodedResponseBody != null)
Log.d("LT", "decodedResponseBody :"+decodedResponseBody);
else
Log.d("LT", "responseBody = null");
} else {
try {
Log.d("LT", "response not successful: error: (" + response.errorBody().string()+") message: ("+response.message()+")");
if (response != null) {
Log.d("LT", "response != null ");
String decodedResponseBody = response.body().toString();
Log.d("LT", "Response Body: "+ decodedResponseBody+" raw: "+response.raw() + " headers: " + response.headers());
} else {
Log.d("LT", "response == null");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call call, Throwable t) {
//Handle failure
Log.d("LT", t.getMessage());
}
});
我的服務接口
public interface MyService {
@POST("sessions")
Call<Void> session(@Header("Content-Type") String contentType, @Body RequestBody body);
}
MyServiceGenerator
public class MyServiceGenerator {
public static final String API_BASE_URL = "http://...";
// Here we add an interceptor in order to be able to listen the most typical messages
private static LoggingInterceptor myLoggingInterceptor = new LoggingInterceptor();
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();//.addInterceptor(myLoggingInterceptor);
private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(API_BASE_URL).addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient.build()).build();
return retrofit.create(serviceClass);
}
}