邮递员说明:
接口:
public interface PostService {
@Headers("Content-Type: application/json")
@FormUrlEncoded
@POST("/user/login")
Call<User> login(@Body User user);
}
通话功能:
User user = new User("student", "student@gmail.com");
Call<User> noticeList = RetrofitAPI.getService().login(user);
noticeList.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
Log.i("postdata", "v =" + response.body().getId());
}
@Override
public void onFailure(Call<User> call, Throwable throwable) {
Toast.makeText(ActivityLogin.this, "Server taking time try refreshing", Toast.LENGTH_SHORT).show();
}
});
我们如何将json post数据发送到服务器?
答案 0 :(得分:0)
您需要将Call<User> login(@Body User user);
替换为Call<YOURRESPONSEMODEL> login(@Body User user);
之类的响应模型类,然后根据需要更改call function
。要创建响应模型,请使用邮递员的响应并创建模型here
答案 1 :(得分:0)
首先,创建Pojo类:
public class SubscriptionResponseModel {
@SerializedName("mNo")
@Expose
private String mNo;
@SerializedName("pId")
@Expose
private String pId;
@SerializedName("status")
@Expose
private String status;
public String getPId() {
return pId;
}
public void setPId(String pId) {
this.pId = pId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
然后,创建界面:
@POST("subs?")
@FormUrlEncoded
Call<SubscriptionResponseModel> setSubs(@Field("pId") String pId,
@Field("mNo") String mNo,
@Field("status") String status);
获取翻新实例:
private static Retrofit getSubsRetrofitInstance() {
return new Retrofit.Builder()
.baseUrl(GlobalVar.BASE_URL)
.addConverterFactory(GsonConverterFactory.create()).build();
}
在getApiService
中:
public static ApiService getSubsApiService() {
return getSubsRetrofitInstance().create(ApiService.class);
}
现在,调用函数:
ApiService apiService = getSubsApiService();
Call<SubscriptionResponseModel> subcriptionResponse = apiService.setSubs("1", "1", "y");
subcriptionResponse.enqueue(new Callback<SubscriptionResponseModel>() {
@Override
public void onResponse(Call<SubscriptionResponseModel> call, Response<SubscriptionResponseModel> response) {
if (response.isSuccessful()) {
/////print success message
}
}
@Override
public void onFailure(Call<SubscriptionResponseModel> call, Throwable t) {
Log.d("error", t.getMessage());
}
});