Android AsyncAPI ahax query with custom http headers

1.5k views Asked by At

How can I add this http header

contentType: "application/json; charset=utf-8"

to this ajax query?

 public void asyncJson(){

    //perform a Google search in just a few lines of code

    String url = "http://www.mysite.com/Services/GetJson";

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("nNumResults", "100");                                                  

    aq.ajax(url, params, JSONObject.class, new AjaxCallback<JSONObject>() {

        @Override
        public void callback(String url, JSONObject json, AjaxStatus status) {

            if(json != null){

                //successful ajax call, show status code and json content
                Toast.makeText(aq.getContext(), status.getCode() + ":" + json.toString(), Toast.LENGTH_LONG).show();            
            }else{                    
                //ajax error, show error code
                Toast.makeText(aq.getContext(), "Error:" + status.getCode(), Toast.LENGTH_LONG).show();
            }

        }
    });

 } // asyncJson    
1

There are 1 answers

5
marcus.ramsden On BEST ANSWER

I've not got a huge amount of experience with android-query but this looks like this example from their async API documentation should do the trick;

String url = "http://www.mysite.com/Services/GetJson";

AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>();        
cb.url(url).type(JSONObject.class).weakHandler(this, "jsonCb");

cb.header("Content-Type", "application/json; charset=utf-8");
cb.param("nNumResults", "100");

aq.ajax(cb);

Note that when setting params you can also use a Map;

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

Watchout for the gotcha when working with the param method. It will default the "Content-Type" header for you if you haven't already set it.

You should then get back a response to this.jsonCb(String url, JSONObject jsonObject, AjaxStatus status).