Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting user agent in Java httpclient and allow redirects to true

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

like image 995
RenegadeAndy Avatar asked Mar 28 '10 14:03

RenegadeAndy


People also ask

What is LaxRedirectStrategy?

Class LaxRedirectStrategyLax RedirectStrategy implementation that automatically redirects all HEAD, GET, POST, and DELETE requests. This strategy relaxes restrictions on automatic redirection of POST methods imposed by the HTTP specification.

What is CloseableHttpClient in Java?

CloseableHttpClient is an abstract class that represents a base implementation of the HttpClient interface. However, it also implements the Closeable interface.

Is HttpClient Java thread safe?

HttpClient is fully thread-safe when used with a thread-safe connection manager such as MultiThreadedHttpConnectionManager.


2 Answers

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

like image 175
Gerd Riesselmann Avatar answered Oct 16 '22 00:10

Gerd Riesselmann


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"
);
like image 43
Darin Dimitrov Avatar answered Oct 16 '22 00:10

Darin Dimitrov