简体   繁体   中英

How to send POST request in Retrofit 2 (Android)

The method call.enqueue() doesn't call. And I give up to understand why? Please help.

I use Retrofit2 for POST request. This is my simple project example.

I have API service named FaceAPI class. 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). 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. 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"); 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() .

First change to String your 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

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

After that make your requestModel like below:

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

Dont forget!! this request body from okhttp3 , that means you have to 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. I just forgot to Log.i the error message in onFailure(). So the POST request is work with my model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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