1

enter image description here

like this, I want to send json body request to GET API

tried this but not worked

 public static void getQuestionsListApi2(final String requestId, final String timestamp,
                                        final ImageProcessingCallback.downloadQuestionsCallbacks callback,
                                        final Context context) {

    try {
       String url = NetUrls.downloadQuestions;

        final JSONObject jsonBody = new JSONObject();
        jsonBody.put("requestId", requestId);
        jsonBody.put("timestamp", timestamp);
        final String mRequestBody = jsonBody.toString();
        Log.i("params", String.valueOf(jsonBody));
        Log.i("URL", url);
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, **jsonBody**, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.v("TAG", "Success " + jsonObject);
                callback.downloadQuestionsCallbacksSuccess(jsonObject.toString());
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.v("TAG", "ERROR " + volleyError.toString());
            }


        });

        request.setRetryPolicy(new DefaultRetryPolicy(
                DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 0,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        RequestQueue queue = Volley.newRequestQueue(context);
        queue.add(request);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}


        request.setRetryPolicy(new DefaultRetryPolicy(
                DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 0,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


        RequestQueue queue = Volley.newRequestQueue(context);
        queue.add(request);

Here Is the Code that i am using when sending JSONRequest with GET Method i am getting 400 error response from server and server not except the the data in the url form . I am sending The jsonBody object as parameter. any solution.

Eby Jacob
  • 1,292
  • 1
  • 7
  • 26
Kumar Jadhav
  • 99
  • 2
  • 6

3 Answers3

0

If you want to pass Json data in body of GET request, you have to use Query annotation

Call<YourNodelClass> getSomeDetails(@Query("threaded") String threaded, @Query("limit") int limit);

this will pass as Json object {"threaded": "val", "limit": 3}.

i have tried and this one is only working code.

Avinash Ajay Pandey
  • 1,347
  • 10
  • 18
-1

You can use retrofit to send request with body. http://square.github.io/retrofit/

It is easy to use library, example:

@GET("[url node]")
Single<Response<ResponseBody>> doSmt(@Header("Authorization") String token, @Body ListRequest name);

Also, take a look here about get methods with body HTTP GET with request body

UPDATE

GET method with request body is optional here. However, this RFC7231 document says,

sending a payload body on a GET request might cause some existing implementations to reject the request.

which means this isn't recommended. Use POST method to use request body.

Check this table from wikipedia.

Table from wikipedia with http methods

Tschallacka
  • 24,188
  • 10
  • 79
  • 121
Maksym V.
  • 2,491
  • 13
  • 24
-1

Try this code..

Add below dependency into app level gradle file.

    implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

then after make below all seperate class

First Retrofit object create class like below ..

public class ApiClient {
private final static String BASE_URL = "https://dog.ceo/api/breed/";

public static ApiClient apiClient;
private Retrofit retrofit = null;
private Retrofit retrofit2 = null;

public static ApiClient getInstance() {
    if (apiClient == null) {
        apiClient = new ApiClient();
    }
    return apiClient;
}

//private static Retrofit storeRetrofit = null;

public Retrofit getClient() {
    return getClient(null);
}


private Retrofit getClient(final Context context) {

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.readTimeout(60, TimeUnit.SECONDS);
    client.writeTimeout(60, TimeUnit.SECONDS);
    client.connectTimeout(60, TimeUnit.SECONDS);
    client.addInterceptor(interceptor);
    client.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            return chain.proceed(request);
        }
    });

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    return retrofit;
}

}

then make api interface like below ..

public interface ApiInterface {
@POST("login/")
Call<LoginResponseModel> loginCheck(@Body UserData data);
}

make pojo call for server response and user input ..

public class LoginResponseModel {
@SerializedName("message") // here define your json key
private String msg;

public String getMsg() {
    return msg;
}

public void setMsg(String msg) {
    this.msg = msg;
}

}

user Input class

public class UserData {
private String email,password;

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

}

    private void getLogin(){
    ApiInterface apiInterface=ApiClient.getInstance().getClient().create(ApiInterface.class);
    UserData data=new UserData();
    data.setEmail("abc@gmail.com");
    data.setPassword("123456");
    Call<LoginResponseModel> loginResponseModelCall=apiInterface.loginCheck(data);
    loginResponseModelCall.enqueue(new Callback<LoginResponseModel>() {
        @Override
        public void onResponse(Call<LoginResponseModel> call, retrofit2.Response<LoginResponseModel> response) {
            if (response.isSuccessful() &&  response !=null && response.body() !=null){
                LoginResponseModel loginResponseModel=response.body();
            }
        }

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

        }
    });
}

When no need user intercation that time used GET method.

you make pojo class then used below link it generate pojo class paste your json data in.. http://www.jsonschema2pojo.org/

Android Team
  • 11,274
  • 2
  • 26
  • 46
  • 1
    java.lang.IllegalArgumentException: Non-body HTTP method cannot contain @Body getting this error for `public interface ApiInterface { @GET("questions/") Call loginCheck(@Body JSONObject data); }` – Kumar Jadhav May 08 '18 at 10:01
  • **i got same issue :** i want to pass body data(JSON object) in to GET() what i need to do for same? – Arbaz.in Oct 09 '19 at 05:57