上一篇介紹了Android Retrofit的get請求【Android Retrofit使用實例--get請求】
下面介紹post請求
1、GetRequestInterface裏添加post接口,如下:
/**
* 獲取出庫單詳情
* */
@FormUrlEncoded
@POST("api/Order/Detail")
Call<OutWarehouseDetail> getDetail(@Field("id") String id);
// 多個參數實例
// @FormUrlEncoded
// @POST("api/Order/Detail")
// Call<Object> withParams(
// @Field("id") String id
// , @Field("code")String code
// );
2、發送請求,如下:
private void loadDetail(String sCode){
if(!TextUtils.isEmpty(sCode)){
//創建Retrofit對象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://127.0.0.1:8080/")
.addConverterFactory(GsonConverterFactory.create()) //Gson數據轉換器
.build();
//創建網絡請求接口實例
GetRequestInterface request = retrofit.create(GetRequestInterface.class);
Call<OutWarehouseDetail> call = request.getDetail(id);//id爲參數
//發送網絡請求(異步)
call.enqueue(new Callback<OutWarehouseDetail>() {
@Override
public void onResponse(Call<OutWarehouseDetail> call, Response<OutWarehouseDetail> response) {
//Log.i(TAG, "loadDetail->onResponse(MainActivity.java): "+response.body());
OutWarehouseDetail detail = response.body();
//Log.i(TAG, detail.sCode);
}
@Override
public void onFailure(Call<OutWarehouseDetail> call, Throwable t) {
Log.i(TAG, "loadDetail->onFailure(MainActivity.java): "+t.toString() );
}
});
}
}