代码之家  ›  专栏  ›  技术社区  ›  Hideyoshi

改装2-向API发送POSt请求时出现问题

  •  0
  • Hideyoshi  · 技术社区  · 7 年前

    我真的很感激能在这方面得到的任何帮助!抱歉问了这么长的问题。

    我正在创建这个android应用程序,在那里注册,用户将键入他们的电话号码并提交,通过短信获得验证码。

    我已经完成了本教程的学习: https://code.tutsplus.com/tutorials/sending-data-with-retrofit-2-http-client-for-android--cms-27845

    我已经将他们应用程序中的两个字段减少为一个字段-一个电话号码的文本字段,以及下面的提交按钮。此电话号码将发送到API。

    我真的是个新手,我一直在尝试成功地向API发送调用。我已经使用“Postman”桌面应用程序测试了API调用,该API仍然有效并正在响应。。。我只是无法形成有效的请求以发送到API。

    我们的API人员设计的JSON模式。。。对于此活动,只需一个字符串,电话号码:

    {
      "phone_number": "string"
    }
    

    然后,如果它是一个有效的电话号码,而用户不在数据库中,那么您会得到一个200响应

        {
        "message": "string"
        }
    

    或者您可以从API返回400响应

    {
      "error": "string",
      "description": "string"
    }
    

    我的改装接口,称为APIService。java如下所示:

    import retrofit2.Call;
    import retrofit2.http.Field;
    import retrofit2.http.Body;
    import retrofit2.http.FormUrlEncoded;
    import retrofit2.http.POST;
    
    public interface APIService {
    
        @POST("/verifications/signup/send")
        @FormUrlEncoded
        Call<Post> sendPhoneNumber(@Field("phone_number") String phone_number);
    }
    

    我真的是一个新的改型2,以上,我能感觉到一个问题,我不知道如何解决。根据给定的API模式,我发送给API的这个参数应该是“body”。。。。不是“字段”。也许在改装@车身时。。。我不太确定如何在上面的java文件中实现这一点。

    现在,我下面所做的可能真的很愚蠢。。。我不明白应该如何改进java“model”类。我遵循了一个教程,该教程根据响应而不是数据调用对类进行建模。因此,我修改了他们的Post类(我称之为?JSON对象,用于发送单个电话号码)。所以我的博士后课程是这样的:

    public class Post {
    
        @SerializedName("message")
        @Expose
        private String message;
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    
        @Override
        public String toString() {
            //return "Post{" + "message = " + message + '}';
            return "This is a return message string";
        }
    }
    

    老实说,我认为我所做的可能是完全错误的,但我不确定如何设计object(Post)类,因为我甚至不知道这个类将用于什么。。。除了回复?

    public class MainActivity extends Activity {
    
    
        private TextView mResponseTv;
        private APIService mAPIService;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            final EditText phoneNumberEt = (EditText) 
    findViewById(R.id.et_phoneNumber);
    
            Button submitBtn = (Button) findViewById(R.id.btn_submit);
            mResponseTv = (TextView) findViewById(R.id.tv_response);
    
            mAPIService = ApiUtils.getAPIService();
    
            submitBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                String phoneNumber = phoneNumberEt.getText().toString().trim();
                if (!TextUtils.isEmpty(phoneNumber)) {
                    sendPost(phoneNumber);
                }
            }
        });
    }
    
    public void sendPost(String phone_number) {
        mAPIService.sendPhoneNumber(phone_number).enqueue(new Callback<Post>() {
            @Override
            public void onResponse(Call<Post> call, Response<Post> response) {
    
                int statusCode = response.code();
    
                if (response.isSuccessful()) {
                    showResponse("Response code is " + statusCode + ". Submitted successfully to API - " + response.body().toString());
                    Log.i(TAG, "post submitted to API." + response.body().toString());
                }
            }
    
                @Override
                public void onFailure(Call<Post> call, Throwable t) {
    
                    showResponse("Unable to submit post to API.");
                    Log.e(TAG, "Unable to submit post to API.");
                }
            });
        }
    
        public void showResponse(String response) {
            if (mResponseTv.getVisibility() == View.GONE) {
                mResponseTv.setVisibility(View.VISIBLE);
            }
            mResponseTv.setText(response);
        }
    
    }
    

    我的其他文件与上面教程链接中的文件非常相似。这就是我修改的内容,以获得简单的单文本字段版本。

    当我能够联系API并读取响应时,我将把它合并到我正在开发的真实应用程序中。

    目前,该应用程序已经完成,并在我的手机上运行(还有模拟器)。当我提交电话号码时,submit按钮下方的文本字段不会显示任何应该显示的消息。。。所以我确信有一次会有问题

    mAPIService.sendPhoneNumber(phone_number).enqueue(new Callback<Post>() {
                @Override
                public void onResponse(Call<Post> call, Response<Post> response) 
    {
    

    在MainActivity中达到。

    2 回复  |  直到 7 年前
        1
  •  0
  •   AbhayBohra    7 年前

    我认为这个api需要JsonObject中的参数。所以试试这个

    在您的APIService中

    @POST("/verifications/signup/send")
    
    Call<JsonObject> sendPhoneNumber(@Body JsonObject phone_number);
    

    发送数据时使用此

    JsonObject object=new JsonObject();
    
    object.addProperty("phone_number",yourPhoneNumber);
    

    在你的发送方式中

    mAPIService.sendPhoneNumber(object).enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
    
                int statusCode = response.code();
    
                if (response.isSuccessful()) {
                    showResponse("Response code is " + statusCode + ". Submitted successfully to API - " + response.body().toString());
                    Log.i(TAG, "post submitted to API." + response.body().toString());
                }
            }
    
                @Override
                public void onFailure(Call<JsonObject> call, Throwable t) {
    
                    showResponse("Unable to submit post to API.");
                    Log.e(TAG, "Unable to submit post to API.");
                }
            });
        }
    

    请尝试让我知道它是否有效。

        2
  •  0
  •   aditya    7 年前

    根据带有电话号码的JSON模式,需要在API主体中传递电话号码。不要使用@字段注释,而是使用@Body注释,其中参数将是RequestBody类的实例。

    @现场文件 https://square.github.io/retrofit/2.x/retrofit/retrofit2/http/Field.html

    使用字段电话号码创建新的RequestBody类。

    public class RequestBody {
    
       @Expose
       @SerializedName("phone_number")
       private String phoneNumber;
    
       public void setPhoneNumber(String phoneNumber) {
       this.phoneNumber = phoneNumber;
       }
    
       public String getPhoneNumber() {
       return phoneNumber;
       }
    

    在要传递电话号码的活动中,创建RequestBody类的对象,在setPhoneNumber()方法中传递电话号码。然后将此对象作为参数传递到APIService中。

    在MainActivity中。班

    public void sendPost(String phone_number) {
    
    RequestBody requestBody = new RequestBody();
    requestBody.setPhoneNumber(phone_number);
    mAPIService.sendPhoneNumber(requestBody).enqueue(new Callback<Post>() {
            @Override
            public void onResponse(Call<Post> call, Response<Post> response) 
    {
    

    因此,您的APIService将如下所示

    public interface APIService {
    
        @POST("/verifications/signup/send")
        @FormUrlEncoded
        Call<Post> sendPhoneNumber(@Body RequestBody requestBody);
    }