首页 > 解决方案 > 使用改造将数据发布到服务器时出错

问题描述

我正在尝试使用改造将数据从我的应用程序发送到服务器。我正在向接口发送 json 格式的数据。此网络服务可与邮递员一起使用,但在应用程序中使用时会出现以下错误

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 2 column 1 path $

在调试时我可以看到我的数据是正确的 json 格式,如下所示

{
"login_id":39,
"contact_no":"91775668"}

这是我向服务器发送数据的方法

  JSONObject object=new JSONObject();
    try {

        object.put("login_id",loginID);
        object.put("contact_no",mobileNumber);

        Call<OTPResponse>call=userService.getOTP(key,object.toString());
        call.enqueue(new Callback<OTPResponse>() {
            @Override
            public void onResponse(Call<OTPResponse> call, Response<OTPResponse> response) {

                }else {


                }

而我的 POST 方法来自界面

    @Headers("Content-Type:application/json")
    @POST(OTP_URL)
    Call<OTPResponse>getOTP(@Header("API-KEY")String key,@Body String otpdetails);


OTPResponse.java


public class OTPResponse {


    @Expose
    @SerializedName("message")
    private String message;
    @Expose
    @SerializedName("OTP")
    private String OTP;
    @Expose
    @SerializedName("status")
    private boolean status;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getOTP() {
        return OTP;
    }

    public void setOTP(String OTP) {
        this.OTP = OTP;
    }

    public boolean getStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }
}

来自服务器的响应

    {
    "status": true,
    "OTP": "422733",
    "message": "OTP sent successfully."
}

标签: androidretrofit

解决方案


解决方案:

而不是在中写入字符串@Body

Call<OTPResponse>getOTP(@Header("API-KEY")String key,@Body String otpdetails);

用这个:

Call<OTPResponse>getOTP(@Header("API-KEY")String key,@Body JsonObject otpdetails);

并且您的方法调用必须是:

Call<OTPResponse>call=userService.getOTP(key, object);

代替:

Call<OTPResponse>call=userService.getOTP(key,object.toString());

希望能帮助到你。

更新:正如NIKHIL所提到的,尝试添加@FormUrlEncoded以解决Internal server error. 所以,更新后的代码应该是:

@FormUrlEncoded
@POST(OTP_URL)
Call<OTPResponse>getOTP(@Header("API-KEY")String key, @Body JsonObject otpdetails);

现在试试。


推荐阅读