我正在努力将应用程序中的 HTTP 客户端从 Commons HTTP Client v3.x 更改为新的 HTTP Client v4.x。我进行了搜索,但找不到适合以下场景的好示例——您能给我指点有关新 HTTP 客户端的优秀教程/文章吗(类似于 java.net.url 上 SO 上的优秀社区 Wiki 文章)?
(1)设置Cookie策略
(2) 设置 Http 代理 - 定义主机/域以及用户名/密码
目前这是通过以下方式完成的 -
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 凭据在旧的 http 客户端中使用以下代码定义--
client.getState().setCredentials(
new AuthScope(urlObj.getHost(), urlObj.getPort()),
new UsernamePasswordCredentials(username, password)
);
在新的 HTTP 客户端中如何做到这一点?
(4) 声明一个新的 HTTP 方法变量,并为此变量指定方法 - 为 GET 或 POST
目前用于上述内容的代码--
HttpMethodBase method;
method = createPostMethod(url, params, multipart, charset);
method = createGetMethod(url, params, charset);
(5) 向方法添加请求 header -
例如,要将用户代理设置为默认用户代理,请使用以下代码--
method.addRequestHeader(new Header("User-Agent", DEFAULT_USER_AGENT));
最佳答案
(1)cookie 的事情参见 this来自另一个问题
(2)代理:
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("/");
来自:
httpcomponents-client-4.1.3\examples\org\apache\http\examples\client\ClientProxyAuthentication.java
(3)不确定
(4)方法
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");
来自示例的 ClientFormLogin.java
(5) header 字段:
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);
那怎么样? 只需查看示例即可。
关于java-需要显示新 HTTP 客户端 (v4.x) 使用的基本示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9019112/