gpt4 book ai didi

java - 处理 HttpClient 重定向

转载 作者:IT老高 更新时间:2023-10-28 20:47:22 26 4
gpt4 key购买 nike

我正在将一些数据发布到响应 302 Moved Temporarily 的服务器。

我希望 HttpClient 跟随重定向并自动获取新位置,因为我相信这是 HttpClient 的默认行为。但是,我遇到了一个异常并且没有遵循重定向:(

这是相关的代码,任何想法将不胜感激:

HttpParams httpParams = new BasicHttpParams();
HttpClientParams.setRedirecting(httpParams, true);
SchemeRegistry schemeRegistry = registerFactories();
ClientConnectionManager clientConnectionManager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

HttpClient httpClient = new DefaultHttpClient(clientConnectionManager, httpParams)
HttpPost postRequest = new HttpPost(url);
postRequest.setHeader(HTTP.CONTENT_TYPE, contentType);
postRequest.setHeader(ACCEPT, contentType);

if (requestBodyString != null) {
postRequest.setEntity(new StringEntity(requestBodyString));
}

return httpClient.execute(postRequest, responseHandler);

最佳答案

对于 HttpClient 4.3:

HttpClient instance = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy()).build();

对于 HttpClient 4.2:

DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new LaxRedirectStrategy());

对于 HttpClient < 4.2:

DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new DefaultRedirectStrategy() {
/** Redirectable methods. */
private String[] REDIRECT_METHODS = new String[] {
HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME
};

@Override
protected boolean isRedirectable(String method) {
for (String m : REDIRECT_METHODS) {
if (m.equalsIgnoreCase(method)) {
return true;
}
}
return false;
}
});

关于java - 处理 HttpClient 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5169468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com