【发布时间】:2021-03-04 04:56:40
【问题描述】:
url=url+/api/registerotp
我尝试使用此代码但无法正常工作
在原始正文数据中发布请求 = {"mobile_or_email": "0123456789"}
来自服务器的响应
{"status":true,"message":"Otp send Your Number!","otp":6425}
public interface Retrofit_request {
@POST("registerotp")
Call<model> getUser(@Body postd mobile_or_email);}
public class model {
@SerializedName("status")
@Expose
private Boolean status;
@SerializedName("message")
@Expose
private String message;
@SerializedName("otp")
@Expose
private Integer otp;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Integer getOtp() {
return otp;
}
public void setOtp(Integer otp) {
this.otp = otp;
}}
public class RetrofitClient<minstance> {
private static final String BASE_URL=url+"/api/";
private static RetrofitClient minstance;
private Retrofit retrofit;
private RetrofitClient(){
retrofit=new
Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
}
public static synchronized RetrofitClient getInstance(){
if (minstance==null){
minstance=new RetrofitClient();
}
return minstance;
}
public Retrofit_request getApi(){
return retrofit.create(Retrofit_request.class);
}}
主类
postd postd=new postd("8273217888");
Call<model> call = RetrofitClient
.getInstance()
.getApi()
.getUser(postd);
call.enqueue(new Callback<model>() {
@Override
public void onResponse(Call<model> call, Response<model> response) {
String s = null;
s = response.message();
Log.d("data", s);
Log.d("data", "true"+response);
}
@Override
public void onFailure(Call<model> call, Throwable t) {
Toast.makeText(getApplicationContext(), "" + t.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("data t", t.getMessage());
}
});`
public class postd {
@SerializedName("mobile_or_email")
String mobile_or_email;
public postd(String mobile_or_email) {
this.mobile_or_email = mobile_or_email;
}
public String getMobile_or_email() {
return mobile_or_email;
}
public void setMobile_or_email(String mobile_or_email) {
this.mobile_or_email = mobile_or_email;
}
}
log-D/data: trueResponse{protocol=h2, code=200, message=, url=https://example.com/app2/api/registerotp}
我是改装新手,所以请告诉我如何修复它
【问题讨论】:
-
postd类在哪里?您需要将对象转换为 JSON 值,然后才能将其用作@Body参数。通常你会使用 Moshi 或 GSON 之类的东西 -
公开课发布 { @SerializedName("mobile_or_email") String mobile_or_email;公开发布(字符串 mobile_or_email){ this.mobile_or_email = mobile_or_email; } public String getMobile_or_email() { return mobile_or_email; } 公共无效 setMobile_or_email(String mobile_or_email) { this.mobile_or_email = mobile_or_email; } }
-
如果您 100% 确定 Body 只是一组对象,您可以将其设为 Map
。这样您就可以向主体添加单独的参数。但这只是一种方式,不是最佳实践 -
将其添加到问题中
-
是的,它只需要对象
标签: android android-studio retrofit retrofit2