java- require basic examples showing use of new HTTP Client (v4.x)
-
14-11-2019 - |
Question
I am working to change the HTTP client in an application from Commons HTTP Client v3.x to the new HTTP Client v4.x. I searched but could not find good examples for the following scenarios-- can you point me to a good tutorial/article on the new HTTP Client (something similar to the excellent Community Wiki article at SO on java.net.url)?
(1) set Cookie Policy
(2) set Http Proxy- defining host/domain as well as username/password
Currently this is done in the following manner--
Credentials credentials =
( host == null || domain == null || "".equals(host.trim()) ||
"".equals(domain.trim()) ) ?
new UsernamePasswordCredentials(username, password) :
new NTCredentials(username, password, host, domain);
client.getState().setProxyCredentials( AuthScope.ANY, credentials);
(3) Auth credentials are defined in the old http client with the following code--
client.getState().setCredentials(
new AuthScope(urlObj.getHost(), urlObj.getPort()),
new UsernamePasswordCredentials(username, password)
);
What is the way to do this in the new HTTP client?
(4) Declaring a new HTTP Method variable and for this variable, Specifying method- as GET or POST
Code used for the above currently--
HttpMethodBase method;
method = createPostMethod(url, params, multipart, charset);
method = createGetMethod(url, params, charset);
(5) Adding request headers to a method -
For example, to set the user agent as Default user agent, the following code is used--
method.addRequestHeader(new Header("User-Agent", DEFAULT_USER_AGENT));
Solution
(1)cookie thing see this from another question
(2)Proxy:
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 8080),
new UsernamePasswordCredentials("username", "password"));
HttpHost targetHost = new HttpHost("www.verisign.com", 443, "https");
HttpHost proxy = new HttpHost("localhost", 8080);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpGet httpget = new HttpGet("/");
from:
httpcomponents-client-4.1.3\examples\org\apache\http\examples\client\ClientProxyAuthentication.java
(3)Not sure
(4)Method
HttpGet httpget = new HttpGet(url);
HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
"org=self_registered_users&" +
"goto=/portal/dt&" +
"gotoOnFail=/portal/dt?error=true");
From ClientFormLogin.java of example
(5)header field:
HttpGet get = new HttpGet(url);
get.setHeader("Content-Type", "text/html");
get.setHeader("User-Agent","Mozilla/4.0 (MobilePhone SCP-5500/US/1.0) NetFront/3.0 MMP/2.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
get.setHeader("Accept-Charset", Chareset+";q=0.7,*;q=0.7");//"utf-8;q=0.7,*;q=0.7");
get.getParams().setParameter("http.socket.timeout",20000);
How about that? Just see the examples.