Retrofit2 的使用文章已經很多了,鴻洋,Hankkin博客已經寫得很清楚了,我今天試著用使用Retrofit2 結果
出現了一些問題,從網上找了很多沒有找到自己想要的.
我使用Retrofi 是測試登錄的,應為我的服務器只接受json提交形式,所有就不能用鍵值對上傳,這就要用到實體Bean,用實體Retrofit會自動幫轉為Json的,這個王jiji告訴我的.但是我用bean的時候還是會拋異常:”Unable to create @Body converter for class
查了很久才知道是哪裡有問題 :
compile 'com.google.code.gson:gson:2.3'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
這裡的版本converter和retrofit要保持一致,否則converter轉化json會異常,
主要的就是這些,順便貼下代碼:
User user = new User();
user.user_mobile = "13537635231";
user.user_paw = pwd;
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("你的Base URl")
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService apiService = retrofit.create(APIService.class);
Call<LoginInfo> login = apiService.login(user);
login.enqueue(new Callback<LoginInfo>() {
@Override
public void onResponse(Call<LoginInfo> call, Response<LoginInfo> response) {
System.out.println(response.body());
}
@Override
public void onFailure(Call<LoginInfo> call, Throwable t) {
}
});
public interface APIService {
@POST("login")
Call<LoginInfo> login(@Body User user);
}
希望可以幫到有需要的人