HttpClient.getParams() deprecated.我应该使用什么来代替?

2022-09-01 03:56:52

我正在使用apache-httpclient-4.3。我会分析一个http请求,特别是查询字符串参数,但是

@Deprecated
public HttpParams getParams()
Deprecated. (4.3) use constructor parameters of configuration API provided by HttpClient

我不确定这是否理解这意味着什么。我应该使用一些配置API的构造函数参数(那是什么?主机配置不再作为类提供)。但是在构建阶段,我直接通过url传递查询参数:

HttpGet request = new HttpGet("http://example.com/?var1=value1&var2=value2");

我找不到一种方法来从我的请求对象中读回参数(var1,var2),而不使用不推荐使用的方法,这应该很简单,因为从对象中获取属性。


答案 1

您可以使用 URIBuilder 对象

URIBuilder builder = new URIBuilder("http://example.com/");
builder.setParameter("var1", "value1").setParameter("var2", "value2");

HttpGet request = new HttpGet(builder.build());

// get back the url parameters   
List<NameValuePair> params = builder.getQueryParams();

我认为您对客户端或HttpMethod的方法有点困惑,不返回URL参数或类似的东西,返回客户端参数,如连接超时,代理,Cookie...等getParams()getParams()

在 4.3.2 之前,您可以使用该方法将参数设置为客户端(现已弃用),在 4.3.2 之后,您可以使用getParams()RequestConfigBuilder

Builder requestConfigBuilder = RequestConfig.custom();
requestConfigBuilder.setConnectionRequestTimeout(1000).setMaxRedirects(1);

,然后设置为唯一(不像以前那样设置为客户端)HttpMethod

request.setConfig(requestConfigBuilder.build());

更新:

如果要从 或 请求对象获取 URI 参数,可以采用相同的方式使用HttpGetHttPostURIBuilder

HttpGet request = new HttpGet("http://example.com/?var=1&var=2");

URIBuilder newBuilder = new URIBuilder(request.getURI());
List<NameValuePair> params = newBuilder.getQueryParams(); 

答案 2

推荐