Search code examples
androidapihttpretrofitretrofit2

Retrofit2 returns 999 when I called api


I use Retrofit2 to call api, when I do apiTest("http://xxx.xx.xx.xxx:xxxx/", "T001", "Futek10911-01"), the response.code is 999 but it returns correct value in Postman. Where's the problem?

    private void apiTest(String url, String machId, String check) throws JSONException {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    MyAPIService myAPIService = retrofit.create(MyAPIService.class);
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("MACHID", machId);
    jsonObject.put("CHECK", check);

    Call<GetHostTime> call = myAPIService.getHostTime("sRequest", jsonObject);
    call.enqueue(new Callback<GetHostTime>() {
        @Override
        public void onResponse(Call<GetHostTime> call, Response<GetHostTime> response) {
            if(response.isSuccessful()){
                Log.d("response ", "isSuccessful");
            }else {
                Log.d("response code ", response.code() + "");
            }
        }

        @Override
        public void onFailure(Call<GetHostTime> call, Throwable t) {
            Log.d("Failure", t.getMessage());
        }
    });

public interface MyAPIService {
@POST("TcLeaseParkAPI/api/ParkingAPI/GetHostTime")
@FormUrlEncoded
Call<GetHostTime> getHostTime(@Field("MACHID") String key, @Field("CHECK") JSONObject jsonObject);

} postman log


Solution

  • Comparing your Postman request and your code. It is clear I feel you are sending the request in wrong manner.

    So we modify your Retrofit request as follows

    public interface MyAPIService {
    @POST("TcLeaseParkAPI/api/ParkingAPI/GetHostTime")
    @FormUrlEncoded
    Call<GetHostTime> getHostTime(@Field("sRequest") JSONObject jsonObject);
    

    And then your request Call as follows

     Call<GetHostTime> call = myAPIService.getHostTime(jsonObject);
    

    Now your JSONObject will go in the key sRequest