이제 302를 사용하는 서버에서 파일을 다운로드하려고합니다. 다운로드 요청에 대한 요청을 리디렉션합니다. 서버 코드를 다운로드 할 때 아래 코드를 사용하면 서버가 응답하지 않습니다. 파일을 다운로드하기 위해 브라우저를 사용하지 않는다는 것을 알고 있습니다. 브라우저를 사용할 때 제대로 작동하고 파일이 맞습니다.서버에서 파일을 다운로드하지 못했습니다.
내 코드에서 문제가 어디에 있는지 알 수 있습니까? 감사합니다.
이
내 코드입니다 :@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);
}
}
치어 :
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.2.3</version>
</dependency>
네 서버가 302를 사용하여 요청을 리디렉션하고 두 번째 요청에서 문제가 발생한다고 생각합니다. 그러나이 문제를 해결하는 방법을 모르겠으며이 튜토리얼을 읽어 주셔서 감사합니다. – Felix
httpclient가 브라우저와 달리 요청을 자동으로 재전송하지 않을 것이라고 생각합니다. 설명서에서는 리디렉션 된 위치를 가져 와서 다른 요청을해야한다고 제안합니다. (나는 생각한다 :) –
httpClient.execute 나는이 메소드를 한 번만 호출한다.) httplient3.x가 httpclient4.x와 다른가? – Felix