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";

Morton
  • 5,380
  • 18
  • 63
  • 118

4 Answers4

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);
    }
}
Komal12
  • 3,340
  • 4
  • 16
  • 25
Mukeshkumar S
  • 785
  • 1
  • 14
  • 30
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";
         }
    };
ashkhn
  • 1,642
  • 1
  • 13
  • 18
  • Yeah I know. But seems it doesn't work for OP that's why I posted the manual way of doing it – ashkhn Apr 19 '17 at 04:10
  • Thanks for your responding man , i try to use `@Override public String getBodyContentType(){ return "application/json"; }` , it shows 'org.json.JSONException: Value – Morton Apr 19 '17 at 04:19
  • 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 @akash93 – OneCricketeer Apr 19 '17 at 04:25
  • So i try to use application/json , let the data `{ "d": "{\"Msg\":\"Successful [0000]"....`handle easily – Morton Apr 19 '17 at 04:28
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; 
        } 
    };
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • My data is not correct that is ` {"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. – Morton Apr 19 '17 at 04:16
  • Alright, maybe you will need to override `getHeaders()`, then – OneCricketeer Apr 19 '17 at 04:21
  • It' fine , thanks your answer about `new JsonObjectRequest(url, null,` – Morton Apr 19 '17 at 04:26
  • 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 earler – ashkhn Apr 19 '17 at 04:44
  • @akash93 I tried the request myself. It returns JSON when the header is added – OneCricketeer Apr 19 '17 at 13:15
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);
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Rajesh N
  • 6,198
  • 2
  • 47
  • 58
  • 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. – ashkhn Apr 19 '17 at 04:06