Android应用程序中的自定义用户代理

时间:2014-04-29 23:49:07

标签: java android http rest android-volley

我尝试在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值?

1 个答案:

答案 0 :(得分: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;
}