Setting user agent in Java httpclient and allow redirects to true

20,186

Solution 1

HttpClient httpclient = new HttpClient();
httpclient.getParams().setParameter(
    HttpMethodParams.USER_AGENT,
    "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"
);

Solution 2

With HttpClient 4.0, the following worked for me:

import org.apache.http.params.HttpProtocolParams;

HttpClient httpclient = new HttpClient();
HttpProtocolParams.setUserAgent(httpclient.getParams(), "My fancy UA");

HttpProtocolParams resides in the httpcore JAR file: http://hc.apache.org/httpcomponents-core/download.html

Solution 3

Use AndroidHttpClient, and pass the user agent as a parameter to newInstance:

AndroidHttpClient client = AndroidHttpClient.newInstance(String userAgent);

There are other good reasons to use AndroidHttpClient instead of the raw HttpClient as well.

Share:
20,186

Related videos on Youtube

RenegadeAndy
Author by

RenegadeAndy

Updated on March 09, 2020

Comments

  • RenegadeAndy
    RenegadeAndy about 4 years

    I am trying to set my user agent string in the HttpClient apache object in Java but I cannot find out how to do it.

    Please help!

    Also I am trying to enable redirects to true but also cannot find this option within the HttpClient object.

    Thanks

    Andy

  • Darin Dimitrov
    Darin Dimitrov about 14 years
    org.apache.commons.httpclient.params.HttpMethodParams: hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/…
  • RenegadeAndy
    RenegadeAndy about 14 years
    Hmm - im not using any libs atm, under org.apache.commons all i have is logging.... can you just tell me the appropriate string to put in there- what does HttpMethodParams.USER_AGENT actually conform to
  • Darin Dimitrov
    Darin Dimitrov about 14 years
    What redirect? Here's a list of common properties: hc.apache.org/httpclient-3.x/preference-api.html
  • RenegadeAndy
    RenegadeAndy about 14 years
    Hmm had a problem and somebody told me to enable redirects. Anyways - the idea of my app is its running on an android based fone - connects and logs into a website, and retrieves some data displaying it to the user. The problem was - the website was returning a different page than when i visited on my pc (hence user agent change) however now its giving me a bad socket error on line 253 pastebin.com/nUkq2Q3G Any ideas whats wrong.
  • kostmo
    kostmo about 14 years
    You should tag this question as "android".
  • Paulo Cheque
    Paulo Cheque over 10 years
    You may try using the deprecated CoreProtocolPNames.USER_AGENT instead. hc.apache.org/httpcomponents-core-4.3.x/httpcore/apidocs/org‌​/…

Related