Android Generic User Agent (UA)

前端 未结 5 1769
你的背包
你的背包 2020-12-31 12:27

I am building an Android app to display content feed from a server. The server is a mobile website (like http://m.google.com) which tracks the traffic from various mobile cl

5条回答
  •  余生分开走
    2020-12-31 12:50

    To change the user agent you need to send a custom User-Agent: header with your HTTP request. Assuming you're using the Android org.apache.http.client.HttpClient class, you have two options:

    1. Set the user agent header on each request. You do this by calling setHeader() on your HttpRequest (HttpPost, HttpGet, whatever) object after you create it:
    HttpGet get = new HttpGet(url);
    get.setHeader("User-Agent", myUserAgent);
    
    1. Change the default User Agent parameter, which will affect all future instances of that HttpClient class. You do this by reading the HttpParams collection from your client with getParams() then updating the user agent using setParameter():
    DefaultHttpClient http = new DefaultHttpClient(); 
    http.getParams().setParameter(CoreProtocolPNames.USER_AGENT, myUserAgent);
    

    If you want to append instead of replace the user agent, you can read the existing one first, change it, and set it back using either of the above methods.

    EDIT:

    Since you said you're using the WebView view you will need to use the WebSettings customization point there. It's basically the same process. Before you call whichever load() method (loadUrl, loadData, etc) you do set the user agent. The changed user-agent will persist as long as that instance of the WebView is around, so you'd do this in the onCreate() of your Activity:

    view = (WebView)findViewById(R.id.webview);
    view.getSettings().setUserAgentString(myUserAgent);
    

    Again, if you want to append instead of replace, use getUserAgentString() to read it, then update it and set it back again.

提交回复
热议问题