使用自定义http标头的Android AsyncAPI ahax查询

时间:2013-12-19 18:49:37

标签: android ajax http header aquery

如何添加此http标头

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

到这个ajax查询?

 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 个答案:

答案 0 :(得分:3)

我没有获得大量的android-query经验,但看起来这个例子来自他们的async API documentation应该做的伎俩;

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

请注意,设置参数时,您还可以使用地图;

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

使用param方法时注意gotcha。如果您尚未设置它,它将默认为“Content-Type”标题。

然后您应该回复this.jsonCb(String url, JSONObject jsonObject, AjaxStatus status)