上一篇介绍了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() );
}
});
}
}
|