【问题标题】:Custom User-Agent in android applicationandroid应用程序中的自定义用户代理
【发布时间】:2014-04-29 23:49:07
【问题描述】:

我尝试在 Android 设备上编写 Rest 客户端。 Web 服务需要自定义 User-Agent 值。我通过以下方式设置:

        JsonObjectRequest(Request.Method.POST, url, object, new Response.Listener<JSONObject>( protected Map<String, String> getParams() throws AuthFailureError {
//some code
                        final HashMap<String, String> map = new HashMap<String, String>(super.getParams());
                        map.put("User-Agent", "Custom-Agent 1.0");
                        map.put("Content-Type","application/json");
                        return map;
                    }
                };

但是服务器收到:

Dalvik/1.4.0 (Linux; U; Android 2.3.3; sdk Build/GRI34)

如何使用自定义User-Agent值?

【问题讨论】:

    标签: java android http rest android-volley


    【解决方案1】:

    我认为您需要覆盖 getHeaders() 来设置用户代理——您正在覆盖 getParams()。不是一回事。

    /* (non-Javadoc)
     * @see com.android.volley.Request#getHeaders()
     */
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = super.getHeaders();
    
        if (headers == null || headers.equals(Collections.emptyMap())) {
            headers = new HashMap<String, String>();
        }
    
        headers.put("User-Agent", "Custom-Agent 1.0");
        // probably don't need to set the content-type here -- 
        // it should be set for you by Volley
        //headers.put("Content-Type", "application/json");
    
        return headers;
    }
    

    【讨论】:

    • 愚蠢的错误。非常感谢;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-03
    • 1970-01-01
    相关资源
    最近更新 更多