views:

410

answers:

2

Hey guys - 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

A: 
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"
);
Darin Dimitrov
I dont seem too have access to the HttpMethodParams package...
RenegadeAndy
`org.apache.commons.httpclient.params.HttpMethodParams`: http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/params/HttpMethodParams.html
Darin Dimitrov
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
RenegadeAndy
`http.useragent`.
Darin Dimitrov
sweet cheers- and the redirect!?
RenegadeAndy
What redirect? Here's a list of common properties: http://hc.apache.org/httpclient-3.x/preference-api.html
Darin Dimitrov
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 253http://pastebin.com/nUkq2Q3GAny ideas whats wrong.
RenegadeAndy
If you want to enable automatic redirects try: `httpclient.setFollowRedirects(true)`. This will automatically follow to the redirected location if the server sends a status code 302 for example.
Darin Dimitrov
Thing is - i dont get that method ...its very strange -im not sure if i got the latest apache jakarta lib if it would work on android - or if you can even use jars with android.
RenegadeAndy
You should tag this question as "android".
kostmo
A: 

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

Gerd Riesselmann