Java HttpClient 4.3更改的参数(查询)处理?

Java HttpClient 4.3更改的参数(查询)处理?,java,httpclient,apache-httpclient-4.x,Java,Httpclient,Apache Httpclient 4.x,我确信我遗漏了一些东西,但对于我来说,当涉及到参数时,HttpClient发送请求的行为是不同的 问题是,任何带有参数的请求都会导致状态代码501。 在4.2版本中,这些请求得到了正确的处理 棘手的部分是,参数没有任何空间性,当参数通过URIBuilder构建时,问题也存在于原告身上,如下所述: 我想我需要一种方法来放置params:BasicHttpsParams集合,而不是将它们与普通uri连接起来——因为它们不会以这种方式被HttpGet识别。此时4.2和4.3之间是否发生了变化 下面是

我确信我遗漏了一些东西,但对于我来说,当涉及到参数时,HttpClient发送请求的行为是不同的

问题是,任何带有参数的请求都会导致状态代码501。 在4.2版本中,这些请求得到了正确的处理

棘手的部分是,参数没有任何空间性,当参数通过URIBuilder构建时,问题也存在于原告身上,如下所述:

我想我需要一种方法来放置params:BasicHttpsParams集合,而不是将它们与普通uri连接起来——因为它们不会以这种方式被HttpGet识别。此时4.2和4.3之间是否发生了变化

下面是如何实现get方法的代码:

private static CloseableHttpClient httpAgent = initializeCloseableHttpClient(connectionManager);

private static CloseableHttpClient initializeCloseableHttpClient(PoolingHttpClientConnectionManager connectionManager) {
    RequestConfig requestConfig = RequestConfig.custom()
                               .setConnectTimeout(500)
                               .setConnectionRequestTimeout(DEFAULT_CONNECTION_TIMEOUT)
                               .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
                               .build();

    ConnectionConfig connectionConfig = ConnectionConfig.custom()
                               .setCharset(StandardCharsets.UTF_8)
                               .build();

    CloseableHttpClient httpClient = HttpClients.custom()
                               .setConnectionManager(connectionManager)
                               .setDefaultRequestConfig(requestConfig)
                               .setDefaultConnectionConfig(connectionConfig)
                               .build();
     return httpClient;
}

public static String get(String url, Map<String, String> arguments) {
    String argumentString = getArgumentString(arguments == null ? EMPTY_COLLECTION : arguments.entrySet());
    HttpGet getMethod = new HttpGet(url + argumentString);
    return request(getMethod, null);
}

private static String request(HttpUriRequest method, AuthenticationDetails authenticationDetails) {
    InputStreamProcessor processor = new CopyToStringInputStreamProcessor();
    processStream(method, authenticationDetails, processor);
    return (String) processor.getResult();
}

 private static void processStream(HttpUriRequest method, AuthenticationDetails authenticationDetails, InputStreamProcessor processor) {
    try {
        HttpClientContext context = null;
        if (authenticationDetails != null) {

            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(authenticationDetails.getUsername(), authenticationDetails.getPassword());
            credsProvider.setCredentials(new AuthScope(method.getURI().getHost(), method.getURI().getPort()), credentials);

            // Create AuthCache instance
            AuthCache authCache = new BasicAuthCache();
            // Generate BASIC scheme object and add it to the local auth cache
            BasicScheme basicAuth = new BasicScheme();
            HttpHost targetHost = new HttpHost(method.getURI().getHost(), method.getURI().getPort(), method.getURI().getScheme());
            authCache.put(targetHost, basicAuth);

            // Add AuthCache to the execution context
            context = HttpClientContext.create();
            context.setCredentialsProvider(credsProvider);
            context.setAuthCache(authCache);
        }

        for (int i = 0; i < 3; i++) {
            CloseableHttpResponse response = httpAgent.execute(method, context);

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200 && statusCode != 302) { // redirect is also ok
                throw new HttpClientException(String.format("A http request responds with failure code: %d (%s), requested uri: %s", statusCode, response.getStatusLine().getReasonPhrase(), method.getRequestLine().getUri()));
            }

            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    try (InputStream responseStream = entity.getContent()) {
                        processor.process(responseStream);
                        EntityUtils.consume(entity);
                    }
                    catch (IOException ex) {
                        throw ex; // In case of an IOException the connection will be released back to the connection manager automatically
                    }
                    catch (RuntimeException ex) {
                        method.abort(); // In case of an unexpected exception you may want to abort the HTTP request in order to shut down the underlying connection and release it back to the connection manager.
                        throw ex;
                    }
                }
            } finally {
                response.close();
            }
        }
    }
    catch (IOException e) {
        throw new HttpClientException(String.format("IO exception while processing http request on url: %s. Message: %s", method.getRequestLine().getUri(), e.getMessage()), e);
    }
    catch (Exception e) {
        throw new HttpClientException(String.format("Exception while processing http request on on url: %s. Message: %s", method.getRequestLine().getUri(), e.getMessage()), e);
    }
}
private static CloseableHttpClient-httpAgent=initializeCloseableHttpClient(connectionManager);
私有静态CloseableHttpClient初始化CloseableHttpClient(PoolighttpClientConnectionManager连接管理器){
RequestConfig RequestConfig=RequestConfig.custom()
.setConnectTimeout(500)
.setConnectionRequestTimeout(默认连接超时)
.setSocketTimeout(默认\u套接字\u超时)
.build();
ConnectionConfig ConnectionConfig=ConnectionConfig.custom()
.setCharset(标准字符集.UTF_8)
.build();
CloseableHttpClient httpClient=HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
.setDefaultConnectionConfig(connectionConfig)
.build();
返回httpClient;
}
公共静态字符串get(字符串url、映射参数){
String argumentString=getArgumentString(arguments==null?空集合:arguments.entrySet());
HttpGet getMethod=新的HttpGet(url+argumentString);
返回请求(getMethod,null);
}
私有静态字符串请求(HttpUriRequest方法,AuthenticationDetails AuthenticationDetails){
InputStreamProcessor处理器=新的CopyToStringInputStreamProcessor();
processStream(方法、身份验证详细信息、处理器);
返回(字符串)处理器。getResult();
}
私有静态void processStream(HttpUriRequest方法、AuthenticationDetails AuthenticationDetails、InputStreamProcessor){
试一试{
HttpClientContext上下文=null;
if(authenticationDetails!=null){
CredentialsProvider credsProvider=新的BasicCredentialsProvider();
UsernamePasswordCredentials credentials=新的UsernamePasswordCredentials(authenticationDetails.getUsername(),authenticationDetails.getPassword());
credsProvider.setCredentials(新的AuthScope(方法.getURI().getHost(),方法.getURI().getPort()),凭证);
//创建AuthCache实例
AuthCache AuthCache=new BasicAuthCache();
//生成基本方案对象并将其添加到本地身份验证缓存
碱性血红素碱性血红素=新碱性血红素();
HttpHost targetHost=新的HttpHost(method.getURI().getHost(),method.getURI().getPort(),method.getURI().getScheme());
authCache.put(targetHost,basicAuth);
//将AuthCache添加到执行上下文
context=HttpClientContext.create();
context.setCredentialsProvider(credProvider);
setAuthCache(authCache);
}
对于(int i=0;i<3;i++){
CloseableHttpResponse response=httpAgent.execute(方法,上下文);
int statusCode=response.getStatusLine().getStatusCode();
如果(statusCode!=200&&statusCode!=302){//重定向也可以
抛出新的HttpClientException(String.format(“http请求响应失败代码:%d(%s),请求的uri:%s”),状态代码,响应.getStatusLine().getReasonPhrase(),方法.getRequestLine().getUri());
}
试一试{
HttpEntity=response.getEntity();
如果(实体!=null){
try(InputStream responseStream=entity.getContent()){
处理程序(responseStream);
EntityUtils.consume(实体);
}
捕获(IOEX异常){
throw ex;//如果发生IOException,连接将自动释放回连接管理器
}
捕获(RuntimeException ex){
method.abort();//如果发生意外异常,您可能希望中止HTTP请求,以便关闭基础连接并将其释放回连接管理器。
掷骰子;
}
}
}最后{
response.close();
}
}
}
捕获(IOE异常){
抛出新的HttpClientException(String.format(“处理url上的http请求时发生IO异常:%s.Message:%s”,method.getRequestLine().getUri(),e.getMessage()),e);
}
捕获(例外e){
抛出新的HttpClientException(String.format(“在url上处理http请求时发生异常:%s.Message:%s”,method.getRequestLine().getUri(),e.getMessage()),e);
}
}
任何可能出错的建议都将受到高度赞赏


谢谢

5xx是服务器错误。在查看服务器日志之前,没有理由认为客户端有任何错误。如果您无法访问服务器日志,请检查响应文本,其中可能有服务器故障的指示。

问题在于以下循环:

for (int i = 0; i < 3; i++) {...}
for(inti=0;i<3;i++){…}
我不知道w