'How to send Body Data to GET Method Request android

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.



Solution 1:[1]

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.

Solution 2:[2]

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("[email protected]");
    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/

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Avinash Ajay Pandey
Solution 2 Mobile Team ADR-Flutter
Solution 3 Community