0

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    
Mario
  • 13,941
  • 20
  • 54
  • 110

1 Answers1

3

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).

marcus.ramsden
  • 2,633
  • 1
  • 22
  • 33
  • thanks, but this sample does not have parameters for the http post, the json is not returned if I don't add parameters to http post. – Mario Dec 20 '13 at 02:22
  • I've added a note about setting the parameters. – marcus.ramsden Dec 21 '13 at 09:47
  • I get this error...Description Resource Path Location Type The method type(Class) in the type AbstractAjaxCallback> is not applicable for the arguments (Class) MainActivity.java /myapp/src/com/ultimate/millionquotes line 92 Java Problem – Mario Dec 24 '13 at 19:21
  • My mistake, lifted the example from the Android Query docs. That should be `cb.url(url).type(JSONObject.class)`. I've corrected the example. – marcus.ramsden Dec 24 '13 at 20:24
  • Thank you very much! and I wish you a Merry Christmas! – Mario Dec 25 '13 at 14:13