我学会了解从URL实际链接重定向的位置。 在重定向URL网站上的testinf之后,它给出了url重定向类型301。 所以,我根据下面的链接进行测试,以获得真正的链接。 Get hold of redirect url with Java org.apache.http.client
代码如下所示:
HttpGet httpget = new HttpGet(filename);
HttpContext context = new BasicHttpContext();
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute((HttpUriRequest) httpget, context);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
throw new IOException(response.getStatusLine().toString());
HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
String currentUrl = currentHost.toURI() + currentReq.getURI();
System.out.println(currentUrl);
但我收到了这条消息:
AbstractHttpClient类型中的方法execute(HttpUriRequest,HttpContext)不适用于参数(HttpGet,HttpContext)
有些人会帮助我,这段代码有什么问题吗?
答案 0 :(得分:1)
使用此httpclient依赖项,您的代码适用于我:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.1.2</version>
</dependency>
并使用这些导入:
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
检查您是否使用了正确的依赖项。