public interface API {
@GET("Login")
Call<ResponseBody> getNews(@Query("username") String userName, @Query("password") String password);
@FormUrlEncoded
@POST("Login")
Call<ResponseBody> postCheck(@Field("username") String userName, @Field("password") String password);
}
public void getRetrofit() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)//url:服務器地址
.build() ;
API api = retrofit.create(API.class) ;
Call<ResponseBody> newsCall = api.getNews("xxx" , "xxx" );//參數
newsCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
try {
Log.e("TAG" , response.body().string() + "") ;
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("TAG" , t.toString() + "") ;
}
});
}
public void postRetrofit(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.build();
API api = retrofit.create(API.class) ;
Call<ResponseBody> call = api.postCheck("xxx" , "xxx" ) ;//參數
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
try {
Log.e("TAG" , response.body().string()+"");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, ""+t.toString(), Toast.LENGTH_SHORT).show();
}
});
}
注:post請求時遇到的問題
① :
@POST("Login")
Call<ResponseBody> postCheck(@Query("username") String userName, @Query("password") String password);
當我用與GET相同的寫法寫POST請求時,出現以下錯誤:
先是在打印log日誌的地方出現空指針,隨後斷點調試發現請求格式無效。原因未找到,如知曉,麻煩留言告訴我,謝謝!
②:
隨後谷歌了一波,我更改了接口申明:
@FormUrlEncoded
@POST("Login")
Call<ResponseBody> postCheck(@Query("username") String userName, @Query("password") String password);
我忘記在那篇博客看到的,說這個 @FormUrlEncoded 註解必不可少(POST中)。結果如下:
調用API接口中的方法時直接崩潰,斷點調試結果:找不到本地變量。原因未明,如知曉,麻煩留言告訴我,謝謝!
③:
根據log日誌提示,最終更改爲:
@FormUrlEncoded
@POST("Login")
Call<ResponseBody> postCheck(@Field("username") String userName, @Field("password") String password);
編譯通過。
這是從https://www.jianshu.com/p/0fda3132cf98博主那兒抄下來的,希望對你們有用!