AnZ AnZ - 6 months ago 128
Android Question

Retrofit - POST request with @Path and without parameters

The request to API as follows:


POST /verify/phone/{userid}/

Mandatory parameters: userid (integer)

Return: nothing


I receive
Bad Request
error all the time if I want to verify user with id 1 (for example):

Response{protocol=http/1.1, code=400, message=Bad Request, url=http://dummyapi.com/verify/phone/1/}


Posting the same request using Postman works well.

Code:

@POST("/verify/phone/{userid}/")
Call<String> postVerifyPhone(@Path("userid") int userId);


public void postVerifyPhone(int userID){
showProgressBar();

RestClient.GitApiInterface service = RestClient.getClient();
Call<String> call = service.postVerifyPhone(userID);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Response<String> response) {
hideProgressBar();

if (response.isSuccess()) {
String result = response.body();
} else {
Log.d("Fail: ", response.body()); //everytime here with Bad Request
}
}

@Override
public void onFailure(Throwable t) {
hideProgressBar();
}
});
}


I'm using String as the return type since there's message returned when there're no user with requested ID in db.

What could be a cause?

Answer Source

I am calling below code for reading response data.

public void postVerifyPhone(int userID){
          RestAdapter restAdapter = new RestAdapter.Builder()
                 .setEndpoint(Constants.URL).build();
          RetrofitApi retrofitApi = restAdapter.create(RetrofitApi.class);
          retrofitApi.postVerifyPhone(userID, new Callback<Response>() {
          @Override
          public void success(Response response, Response response2) {
                BufferedReader reader = null;
                StringBuilder sb = new StringBuilder();
                try {
                    reader = new BufferedReader(new InputStreamReader(response.getBody().in()));
                    String line;
                    try {
                        while ((line = reader.readLine()) != null) {
                            sb.append(line);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }catch (IOException e) {
                    e.printStackTrace();
                }
                  String result = sb.toString();
//                System.out.println("res:" + result.toString());

            }
            @Override
            public void failure(RetrofitError error) {
                hidePDialog();
            }
        });


}

below is postVerifyPhone() code

@FormUrlEncoded
    @POST("/verify/phone/")
    public void postVerifyPhone(@Field("userID") String userID, Callback<Response> resonse);

It is working fine for me.please check it once.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download