3

I need to make a POST-request in android. Before I tried it in Postman and it works fine.

enter image description here

But in Android (I'm using Retrofit2) it don't want to connect with server.

My ApiService:

@POST("home/info/")
Call<ResponseData> getJson(@Body Post post);

My RetrofitClient:

Retrofit.Builder()
            .baseUrl(http://api.beauty.dikidi.ru/)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

My Post body class

private String city_id;

public String getCity_id() {
    return city_id;
}

public void setCity_id(String city_id) {
    this.city_id = city_id;
}

I tried different solutions: @Query, @Field. I tried to play with URL like here. My breakepoint in OnResponse is not reached. Please, help me to set up connection!

Logs from Interceptor

D/OkHttp: <-- 200 OK http://api.beauty.dikidi.ru/home/info/ (474ms)
Server: nginx
Date: Wed, 14 Mar 2018 09:56:27 GMT
Content-Type: application/json; charset="utf-8"
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Set-Cookie: lang=208f1b939dfd656bcfad0eac6c66f41806155878%7Eru; path=/;       domain=.dikidi.ru; HttpOnly
03-14 09:56:25.913 5997-6029/example.TestProject D/OkHttp: 
Expires: Mon, 26 Jul 1990 05:00:00 GMT
Last-Modified: Wed, 14 Mar 2018 09:56:27 GMT
Cache-Control: no-store, no-cache, must-revalidate
Cache-Control: post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: 
cookie_name=3b9f5f43b88487ff1e44e0f6da790f25a8913101%7E5aa8f1cb5b7c31-
92789521; expires=Thu, 15-Mar-2018 09:56:27 GMT; Max-Age=86400; path=/; 
domain=.dikidi.ru; HttpOnly
03-14 09:56:25.914 5997-6029/maxzonov.modersoft_testproject D/OkHttp: {"error":{"code":1,"message":"\u041e\u0448\u0438\u0431\u043a\u0430. city_id - \u043e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u044b\u0439 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440!"},"data":[]}

It shows that connection is OK but parametres are passing incorrectly.

The problem with passing parametres was resolved. Now code inside in Retrofit is not called.

Call snippet:

    ApiService apiService = RetrofitClient.getApiService();
    Call<ResponseData> call = apiService.getJson(CITY_ID);
    call.enqueue(new Callback<ResponseData>() {
        @Override
        public void onResponse(Call<ResponseData> call, Response<ResponseData> response) {
            int status = response.code();
            String count = response.body().getData().getBlock().getShare().getCount();
            Log.d("myLog", count);
            getViewState().showShare(count);
        }

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

        }
    });

2 Answers2

1

Try this

@POST("home/info/{city_id}")
Call<ResponseData> getData(@Path("city_id") int cityId);
Anirudh Goud
  • 346
  • 2
  • 11
0

Here is some steps for call post request in retrofit.

Make http request with retrofit.

public IWebInterface serviceCallApi() {
 HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(Constants.Web.CONNECTION_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(Constants.Web.CONNECTION_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(Constants.Web.CONNECTION_TIMEOUT, TimeUnit.SECONDS);
        builder.addInterceptor(logging);
        OkHttpClient client = builder.build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(add_your_base_url)
                .client(client)
                .addConverterFactory(JacksonConverterFactory.create())
                .build();
        return retrofit.create(IWebInterface .class);
}

Create interface which will append request parameter

public interface IWebInterface {
@POST("home/info/")
@FormUrlEncoded
Call<ResponseData> getJson(@Field("city_id") String title);

}

Now you already created model. fill this model as a body to your retrofit call

 public boolean callApi(){
 boolean isSuccess = false;
 Call<ResponseData> call = serviceCallApi.getJson(pass_your_city);
        try {

            Response<ResponseData> response= call.execute();
            if (response.code() == 200) {
                ResponseData responseParser = response.body();
                if (responseParser != null) {
                    isSuccess = true;                       
                }
            }  
        } catch (IOException e) {
            Log.e("Exception", e.getMessage());
        }
}
 return isSuccess;

}

your model :

public class Post {

    @SerializedName("city_id")
    @Expose
    private String title;           
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }


}

here is the steps i did in my project for call POST retrofit. Hope it will help you!!

Hemant Parmar
  • 3,924
  • 7
  • 25
  • 49