简体   繁体   English

如何在Retrofit 2(Android)中发送POST请求

[英]How to send POST request in Retrofit 2 (Android)

The method call.enqueue() doesn't call. 方法call.enqueue()不调用。 And I give up to understand why? 而且我放弃了为什么? Please help. 请帮忙。

I use Retrofit2 for POST request. 我将Retrofit2用于POST请求。 This is my simple project example. 这是我简单的项目示例。

I have API service named FaceAPI class. 我有名为FaceAPI类的API服务。 Code: 码:

package com.facelocation.testretrofit;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;


public interface FaceAPI {

    @POST("api/auth/register")
    Call<ResponseBody> registerUser(
            @Body RegistrationBody body
    );
}

I have a RegistrationBody class which I'm trying to push on the server in JSON format (two parameters only - email and password). 我有一个RegistrationBody类,我正在尝试以JSON格式(仅两个参数-电子邮件和密码)将其推入服务器。 Code: 码:

package com.facelocation.testretrofit;

public class RegistrationBody {
    public String email;
    public String password;

    public RegistrationBody(String email, String password) {
        this.email = email;
        this.password = password;
    }
}

And I have the simplest MainActivity class with only one button. 我只有一个按钮,拥有最简单的MainActivity类。 Code: 码:

package com.facelocation.testretrofit;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    String TAG = "Reg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("https://face-location.com/")
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();

                FaceAPI api = retrofit.create(FaceAPI.class);
                RegistrationBody reg = new RegistrationBody("somenewemail111@gmail.com", "password12");

                Call<ResponseBody> call = api.registerUser(reg);
                Log.i(TAG, "Works until here");

                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        Toast.makeText(MainActivity.this, "Все прошло хорошо",Toast.LENGTH_SHORT).show();
                        Log.i(TAG, "THIS METHOD DOESN'T CALL! WHY?" + response.toString());

                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });
            }
        });
    }
}

When I run this code I don't get any errors. 当我运行这段代码时,我没有任何错误。 And I don't get any Server Response. 而且我没有任何服务器响应。 This line of code works Log.i(TAG, "Works until here"); 这行代码适用于Log.i(TAG,“直到这里工作”); but next method, I think, doesn't call. 但是我认为下一个方法不会调用。 I can't understand why I didn't get any errors or server response. 我不明白为什么我没有收到任何错误或服务器响应。 Please Help! 请帮忙!

So the problem is mostly seems in your RegistrationBody() . 因此,问题主要出在您的RegistrationBody()

First change to String your RegistrationBody() 首先更改为String您的RegistrationBody()

You are free to use below code to make it: 您可以随意使用以下代码来实现:

public static String modelAsString(Object obj) {
        String value;
        ObjectMapper mapper = new ObjectMapper();
        try {
            value = mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return value;
    }

Which will look like 看起来像

RegistrationBody reg = new RegistrationBody("somenewemail111@gmail.com", "password12");
String modelAsString = modelAsString(req)

And add your mediaType just in the activity like 并在活动中添加您的mediaType

  public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

After that make your requestModel like below: 之后,使您的requestModel如下所示:

RequestBody requestBody = RequestBody.create(JSON, modelAsString);

Dont forget!! 不要忘记! this request body from okhttp3 , that means you have to import okhttp3.RequestBody ; 来自okhttp3的请求正文,这意味着您必须import okhttp3.RequestBody ;

After all make your call like; 毕竟让您喜欢

Call<ResponseBody> call = api.registerUser(requestBody);

Let me know if it works !!!! 让我知道它是否有效!!!!

@Murat Guc thank you for this detailed answer but as suggested @Pavneet_Singh and @Vívêk Båräì the problem was in onFailure() method. @Murat Guc感谢您提供详细的答案,但正如建议的@Pavneet_Singh和@VívêkBåräì一样,问题出在onFailure()方法中。 I just forgot to Log.i the error message in onFailure(). 我只是忘记了onFailure()中的Log.i错误消息。 So the POST request is work with my model. 因此,POST请求适用于我的模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM