0

我正在努力将应用程序中的 HTTP 客户端从 Commons HTTP Client v3.x 更改为新的 HTTP Client v4.x。我进行了搜索,但找不到以下场景的好例子——你能给我指出一篇关于新 HTTP 客户端的好教程/文章(类似于 java.net.url 上 SO 上的优秀社区 Wiki 文章)吗?

(1) 设置 Cookie Policy

(2) 设置 Http Proxy - 定义主机/域以及用户名/密码

目前,这是通过以下方式完成的——

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 Method 变量,并为这个变量指定方法——如 GET 或 POST

目前用于上述的代码——

 HttpMethodBase method;
method = createPostMethod(url, params, multipart, charset);
 method = createGetMethod(url, params, charset);

(5) 将请求头添加到方法中 -

例如,要将用户代理设置为默认用户代理,使用以下代码 -

method.addRequestHeader(new Header("User-Agent", DEFAULT_USER_AGENT));
4

1 回答 1

2

(1)cookie的东西从另一个问题看到这个

(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)标题字段:

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);

那个怎么样?只看例子。

于 2012-03-02T02:29:12.497 回答