Nima Faraji
Nima Faraji

Reputation: 81

Send Header And Data(Body) as String in Volley

I am trying to send a post request to my server
my server read Headers of the request in String Format but getHeaders() in Volley return :
Map< String, String >

Is there any way to send headers of request in string Format ?!

this is my Code Request :

Map<String, String> params = new HashMap<String, String>();
    params.put("MY_FIRST_DATA_KEY", "MY_FIRST_DATA_VALUE");
    params.put("MY_SECOND_DATA_KEY", "MY_SECOND_DATA_VALUE");

    String url = "http://MY_URL.com";

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params), new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.e(TAG, "onResponse: " + response.toString() );
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "onErrorResponse: " + error.toString() );
            error.printStackTrace();
        }
    })
    {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("MY_KEY","MY_VALUE");
            /* HERE i need to return a String Value */
            return headers;
        }
    };

    request.setRetryPolicy(new DefaultRetryPolicy(20000 , 3 , 3));
    Volley.newRequestQueue(context).add(request);

Upvotes: 3

Views: 898

Answers (3)

Dankyi Anno Kwaku
Dankyi Anno Kwaku

Reputation: 1293

This is how I made a volley POST request adding headers and body

private void call_api(final String url){

    if(!this.isFinishing() && getApplicationContext() != null){
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                resultsTextView.setVisibility(View.INVISIBLE);
                loader.setVisibility(View.VISIBLE);
            }
        });

        Log.e("APICALL", "\n token: " + url);


        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("APICALL", "\n response: " + response);
                        if(!FinalActivity.this.isFinishing()){
                            try {
                                JSONObject response_json_object = new JSONObject(response);

                                    JSONArray linkupsSuggestionsArray = response_json_object.getJSONObject("data").getJSONArray("package");
                                    final JSONObject k = linkupsSuggestionsArray.getJSONObject(0);
                                    final String result = k.getJSONArray("action").getJSONObject(0).getString("url");
                                    last_results = result;
                                    last_results_type = k.getString("type");
                                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                                        @Override
                                        public void run() {

                                            loader.setVisibility(View.INVISIBLE);
                                            resultsTextView.setText(result);
                                            resultsTextView.setVisibility(View.VISIBLE);
                                        }
                                    });
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Toast.makeText(getApplicationContext(), "An unexpected error occurred.", Toast.LENGTH_LONG).show();
                                finish();
                            }
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("APICALL", "\n error: " + error.getMessage());
                        Toast.makeText(getApplicationContext(), "Check your internet connection and try again", Toast.LENGTH_LONG).show();
                        finish();
                    }
                }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("apiUser", "user");
                headers.put("apiKey", "key");
                headers.put("Accept", "application/json");
                //headers.put("Contenttype", "application/json");
                return headers;
            }

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<>();
                map.put("location", "10.12 12.32");
                return map;
            }

        };
        stringRequest.setShouldCache(false);
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
    }
}

Upvotes: 0

Mayank Bhatnagar
Mayank Bhatnagar

Reputation: 2191

You can add getParams() in the JsonObjectRequest()

@Override
public Map<String, String> getParams() {
  Map<String, String> params = new HashMap<String, String>();
  params.put("Parameter1", "value");
  params.put("Parameter2", "value");
  return params;
}

Hope it helps.

Upvotes: 0

Navneet Krishna
Navneet Krishna

Reputation: 5017

try overriding getParams()

    @Override
    protected Map<String,String> getParams(){
        Map<String, String> params = new HashMap<String, String>();
        params.put("MY_FIRST_DATA_KEY", "MY_FIRST_DATA_VALUE");
        params.put("MY_SECOND_DATA_KEY", "MY_SECOND_DATA_VALUE");

        return params;
    }

Upvotes: 2

Related Questions