Retrofit2:使用字符串请求发送 POST 请求 [英] Retrofit2: Sending POST request with String request
本文介绍了Retrofit2:使用字符串请求发送 POST 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 android 新手,现在我正在使用 Retrofit 来集成网络服务.
Hi I am new to android and now I am using Retrofit for integrating the web services.
我不明白如何使用 Retrofit POST 请求将参数发送到服务器.
I am not understanding how to send parameters to the server using Retrofit POST request.
请帮帮我.谢谢.
String url = "XXXXXXXXX/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder().baseUrl(url).
addConverterFactory(GsonConverterFactory.create()).build();
PostInterface service = retrofit.create(PostInterface.class);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("email", "device3@gmail.com");
jsonObject.put("password", "1234");
} catch (JSONException e) {
e.printStackTrace();
}
final String result = jsonObject.toString();
service.getStringScalar(result).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
System.out.println("result is====>" + response.body());
}
@Override
public void onFailure(Call<String> call, Throwable t) {
System.out.println("Failuere");
}
});
}
发布界面:-
public interface PostInterface {
@POST("User/DoctorLogin")
Call<String> getStringScalar(@Body String body);
}
推荐答案
创建一个新的模型类:
public class Credentials {
private String email;
private String password;
public Credentials(String email, String password) {
this.email = email;
this.password = password;
}
}
然后修改你的界面:
public interface PostInterface {
@POST("User/DoctorLogin")
Call<String> getStringScalar(@Body Credentials body);
}
然后这样称呼它:
service.getStringScalar(new Credentials("device3@gmail.com", "1234")).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
System.out.println("result is====>" + response.body());
}
@Override
public void onFailure(Call<String> call, Throwable t) {
System.out.println("Failuere");
}
});
这篇关于Retrofit2:使用字符串请求发送 POST 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文