0
现在我试图从服务器上下载一个文件,使用302重定向获取请求到下载资源。当我用下面的代码下载文件时,服务器响应失败我认为服务器知道我不使用浏览器下载文件。当我使用浏览器时,它工作正常,文件是正确的。从服务器下载文件失败
你能告诉我在我的code.thanks问题在哪里。
这是我的代码:
@SuppressWarnings("deprecation")
public static void downloadFile(String url, String fileName, String page) throws InterruptedException, IOException {
httpClient = new DefaultHttpClient(cm);
// set timeout
HttpParams httpParams = httpClient.getParams();
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_SECONDS * 1000);
HttpEntity entity = null;
HttpGet httpGet = new HttpGet(url);
Random r=new java.util.Random(UAS.length);
//Cookie:AJSTAT_ok_times=7
String ua = UAS[r.nextInt(UAS.length)];
httpGet.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31 AlexaToolbar/alxg-3.1");
httpGet.setHeader("Accept-Charset", "UTF-8,utf-8;q=0.7,*;q=0.3");
httpGet.setHeader("Accept-Encoding", "deflate,sdch");
httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
httpGet.setHeader("Cache-Control", "max-age=0");
httpGet.setHeader("Connection", "keep-alive");
httpGet.setHeader("Cookie", "AJSTAT_ok_times=7");
httpGet.setHeader("Host", "www.test.com");
httpGet.setHeader("Cookie", "AJSTAT_ok_times=7");
try {
HttpContext context = new BasicHttpContext();
HttpResponse remoteResponse = httpClient.execute(httpGet, context);
entity = remoteResponse.getEntity();
if (remoteResponse.getStatusLine().getStatusCode() != 200) {
System.out.println(remoteResponse.getStatusLine().getStatusCode());
}
} catch (Exception e) {
httpGet.abort();
e.printStackTrace();
return;
}
// 404返回
if (entity == null) {
System.out.println("404");
return;
}
File file = new File(fileOutPutDIR + page + "/" + fileName + ".rar");
File parent = file.getParentFile();
if (parent.exists() || parent.mkdirs()) {
// ...
} else {
throw new IOException("Failed to create output directory " + parent);
}
System.out.println("downloading..." + file.getName());
InputStream input = entity.getContent();
try {
FileUtils.copyInputStreamToFile(input, file);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(input);
}
}
POM:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.2.3</version>
</dependency>
是的服务器使用302重定向我的请求,我认为问题发生在第二个request.but我不知道如何解决这个问题,我会读这个教程谢谢。 – Felix
我认为httpclient不会自动重定向请求(不像浏览器)。文档建议您需要获取重定向位置并提出另一个请求。 (我认为:)) –
httpClient.execute我只调用这个方法一次):httplient3.x与httpclient4.x是不同的? – Felix