解决这个问题的方法是使用URLEncoder
类手动编码重定向的URL。下面是一个示例代码:
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.IOException;
import java.net.URLEncoder;
public class HttpClientRedirectExample {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// 需要编码的URL
String redirectUrl = "http://example.com/redirect?url=http://example.com/some%20path";
// 手动编码重定向URL
String encodedUrl = URLEncoder.encode(redirectUrl, "UTF-8");
// 创建HTTP GET请求
HttpGet httpGet = new HttpGet(encodedUrl);
// 发送请求并获取响应
CloseableHttpResponse response = httpClient.execute(httpGet);
// 处理响应...
// 关闭响应和HTTP客户端
response.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
在上面的示例中,重定向URL被手动编码为http%3A%2F%2Fexample.com%2Fredirect%3Furl%3Dhttp%3A%2F%2Fexample.com%2Fsome%2520path
,然后使用HttpGet
发送请求。这样可以确保重定向URL在被解析时不会自动解码。