How to send request Header is "Content-Type":"application/json" when GET on Volley
Asked Answered
L

4

8

I try to use GET on Volley , but i need send request to application/json .

I take a look for some answers , i try to use jsonBody , but it shows error:

null com.android.volley.ServerError

Here is my code:

public class MainActivity extends AppCompatActivity {

    String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";
    JSONObject jsonBody;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            //I try to use this for send Header is application/json
            jsonBody = new JSONObject("{\"type\":\"example\"}");
        } catch (JSONException ex) {
            ex.printStackTrace();
        }

        RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,
                new Response.Listener<JSONObject>() {


                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("TAG", response.toString());
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG", error.getMessage(), error);
            }


        });


        mQueue.add(jsonObjectRequest);

    }


}

Is any one can teach me how to fix this , any help would be appreciated.

Here is my url: String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";

Lightweight answered 19/4, 2017 at 3:50 Comment(2)
jsonBody is the body, not a header. You are getting a ServerError, so there is a log message somewhere that you should read instead of the logcatAkimbo
Override your get headers() of request queueBinaural
B
17
@Override 
public Map<String, String> getHeaders() throws AuthFailureError { 
    Map<String, String> params = new HashMap<String, String>();                
    params.put("Content-Type", "application/json");
    return params; 
} 

Implementation in your's

public class MainActivity extends AppCompatActivity {

    String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d("TAG", response.toString());
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("TAG", error.getMessage(), error);
                }
            }) { //no semicolon or coma
            @Override 
            public Map<String, String> getHeaders() throws AuthFailureError { 
                Map<String, String> params = new HashMap<String, String>();                
                params.put("Content-Type", "application/json");
                return params; 
            } 
        };
        mQueue.add(jsonObjectRequest);
    }
}
Binaural answered 19/4, 2017 at 4:6 Comment(9)
Thanks for your responding , where should i put this code ?Lightweight
i got it , thanks for your answer , but it show the result not like post manLightweight
@徐博俊 Your Response is XML Not JSON.Binaural
@徐博俊 Please Check the Image and Let me knowBinaural
I check the web site , the image has been deleteLightweight
Hey , i see your answer again and correct the code, i can get the json data now , but how do you post json and get without dLightweight
Let us continue this discussion in chat.Binaural
@NarendraJi Please Refer this link - https://mcmap.net/q/513034/-volley-timeout-errorBinaural
Some backend frameworks expect a "Accept:application/json" header in their API endpoints. This was my case. After half an hour, adding that header to the code you provided made the trick .Preparator
P
5

In general for setting a custom header you need to override getHeaders and set the custom header manually. However, volley handles content type headers differently and getHeaders way does not always work.

So for your case you need to override getBodyContentType. So your code will look like

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
   Log.d("TAG", response.toString());
}, new Response.ErrorListener(){
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("TAG", error.getMessage(), error);
        }


    }){
         @Override
         public String getBodyContentType(){
              return "application/json";
         }
    };
Peon answered 19/4, 2017 at 4:4 Comment(4)
Yeah I know. But seems it doesn't work for OP that's why I posted the manual way of doing itPeon
Thanks for your responding man , i try to use @Override public String getBodyContentType(){ return "application/json"; } , it shows 'org.json.JSONException: Value <?xml of type java.lang.String cannot be conv' , not like i use Post man GET by application/json , i update my URL on my question.Lightweight
The body comes back as XML without the header. The server processes the header, so maybe the server's you've used don't read that correctly @akash93Akimbo
So i try to use application/json , let the data { "d": "{\"Msg\":\"Successful [0000]"....handle easilyLightweight
A
4

I try to use GET on Volley

The docs for the method you are calling says this

Constructor which defaults to GET if jsonRequest is null, POST otherwise

You can't GET with an HTTP JSON body. Maybe that's the error.

//I try to use this for send Header is application/json
jsonBody = new JSONObject("{\"type\":\"example\"}");

That's not the header, so pass in null here to do GET

new JsonObjectRequest(url, null,

And towards the end of your request, override a method to request JSON

        ... 

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("TAG", error.getMessage(), error);
        }


    }) { // Notice no semi-colon here
        @Override 
        public Map<String, String> getHeaders() throws AuthFailureError { 
            Map<String, String> params = new HashMap<String, String>();                
            params.put("Content-Type", "application/json");
            return params; 
        } 
    };
Akimbo answered 19/4, 2017 at 4:12 Comment(5)
My data is not correct that is <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/">{"Msg":"Successful [0000]".... , but if i use post man send GET by application/json , it will get { "d": "{\"Msg\":\"Successful [0000]".... , So i ask this question.Lightweight
Alright, maybe you will need to override getHeaders(), thenAkimbo
It' fine , thanks your answer about new JsonObjectRequest(url, null,Lightweight
Seems like the real issue is that the json you receive is invalid since it contains the xml tag. Once you fix that your code should work fine without needing to override any methods since the content type header is set automatically by JsonRequest as @cricket_007 mentioned earlerPeon
@akash93 I tried the request myself. It returns JSON when the header is addedAkimbo
B
1

Use String request instead of jsonrequest like this

            StringRequest loginMe = new StringRequest(Request.Method.GET, "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews", new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {

                    System.out.println("LoginActivity -- onResponse --> " + response);

                    if (progressDialog != null) {

                        progressDialog.dismiss();

                    }

                    try {

                        JSONObject jsonObject = new JSONObject(response);

                    } catch (Exception e) {

                        CommonUtility.somethingWentWrongDialog(activity,
                                "LoginActivity -- onResponse-- Exception --> ".concat(e.getMessage()));

                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {

                    if (progressDialog != null) {

                        progressDialog.dismiss();

                    }

                    CommonUtility.somethingWentWrongDialog(activity,
                            "LoginActivity -- onErrorResponse --> ".concat(error.getMessage()));

                }
            }) {

                @Override
                protected Map<String, String> getParams() {

                    Map<String, String> params = new HashMap<>();


                    System.out.println("LoginActivity -- LoginParams --> " + params.toString());

                    return params;

                }
            };

            loginMe.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

            Volley.newRequestQueue(activity).add(loginMe);
Barm answered 19/4, 2017 at 4:3 Comment(1)
Please do not copy paste sample code. Edit it to suit the question requirements. The above code contains random lines which have nothing to do with the question.Peon

© 2022 - 2024 — McMap. All rights reserved.