【问题标题】:HttpPost and HttpGet object to url so as to be able to use with Volley?HttpPost 和 HttpGet 对象到 url 以便能够与 Volley 一起使用?
【发布时间】:2014-09-18 15:34:23
【问题描述】:

Volley 给了我们更好的效率,但是它使用了“url”

JsonObjectRequest j = new JsonObjectRequest((int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener);

但是如果我必须使用 HttpPost 或 HttpGet 对象,因为我必须设置 Header 和 Entity 等。我该如何在仍然使用 Volley 的同时做到这一点。

HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("String", "something" );
httpGet.setHeader("Content-Type","application/json");
...
httpPost.setEntity(new StringEntity("whatever"));

基本上在这几行代码之后,我得到了 HttpPost / HttpGet 对象;有没有办法在 volley 中使用这个对象而不是使用 HttpClient 来执行请求。

或者是否有一些不同的方法来设置标题等,然后将其与 Volley 一起使用。

【问题讨论】:

    标签: java android apache android-volley


    【解决方案1】:

    我认为这可能会帮助您了解这个想法:

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                                    Request.Method.POST,
                                    url,
                                    jsonRequest,
                                    new JSONResponseListener(this),
                                    new JSONResponseErrorListener(this)){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json");
                return headers;
            }
    
            @Override
            protected Map<String, String> getParams()  {
                Map<String, String> params = new HashMap<String, String>();
                params.put("username", username);
                params.put("password", password);
    
                return params;
            }
        };
        MyApplication.getInstance().addToRequestQueue(jsonObjectRequest);
    

    【讨论】:

      【解决方案2】:

      覆盖 Volley 请求对象中的 getHeaders() 方法。然后从该方法返回一个包含标头的映射。

      【讨论】:

      • 谢谢,你知道我在哪里可以找到有关 Volley 的文档吗,developers.android.com 上提供的文档似乎不够用。
      • 就像我想知道如何使用 volley 进行同步请求,这样如果我在队列中添加请求 A、B、C 之后,它们将以相同的顺序执行 A、B、C
      • 据我所知,在这种情况下最好使用其他东西。 Volley 是显式异步和多线程的,因此在您的情况下,A、B 和 C 应该与 Volley 并行运行。
      猜你喜欢
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 2012-02-13
      • 2013-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多