2013-04-17 4 views
0

이제 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> 

답변

0

http://hc.apache.org/httpclient-legacy/redirects.html 난 당신이 리디렉션을 수동으로

을 처리 할 필요가 생각하는 HTTP 문서를보세요 수동으로 리디렉션 처리

300에서 399 사이의 모든 응답 코드는 일부 양식의 응답을 리디렉션합니다. 가장 일반적인 리디렉션 응답 코드는 다음과 같습니다

301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY 
302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY 
303 See Other. HttpStatus.SC_SEE_OTHER 
307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT 

참고 : 간단하게하지 않는 다른 URI가 요청을 전송할 나타내는 3xx의 범위에있는 응답 코드의 숫자가 있습니다. 이 응답 코드는 아래에 나열되어 있으며 처리되는 방식은 응용 프로그램에 따라 다릅니다.

응용 프로그램이 "간단한"리디렉션 응답 중 하나를 받으면 HttpMethod 객체에서 새 URL을 추출하고 해당 URL에서 다운로드를 다시 시도해야합니다. 또한 리디렉션이 순환 루프를 형성하는 경우 따라야 할 리디렉션 수를 제한하는 것이 좋습니다.

연결할 URL을 위치 헤더에서 추출 할 수 있습니다.

String redirectLocation; 
    Header locationHeader = method.getResponseHeader("location"); 
    if (locationHeader != null) { 
     redirectLocation = locationHeader.getValue(); 
    } else { 
     // The response is invalid and did not provide the new location for 
     // the resource. Report an error or possibly handle the response 
     // like a 404 Not Found error. 
    } 

새 위치를 결정한 후에는 정상적으로 연결을 다시 시도 할 수 있습니다. 자세한 내용은 자습서를 참조하십시오.

+0

네 서버가 302를 사용하여 요청을 리디렉션하고 두 번째 요청에서 문제가 발생한다고 생각합니다. 그러나이 문제를 해결하는 방법을 모르겠으며이 튜토리얼을 읽어 주셔서 감사합니다. – Felix

+0

httpclient가 브라우저와 달리 요청을 자동으로 재전송하지 않을 것이라고 생각합니다. 설명서에서는 리디렉션 된 위치를 가져 와서 다른 요청을해야한다고 제안합니다. (나는 생각한다 :) –

+0

httpClient.execute 나는이 메소드를 한 번만 호출한다.) httplient3.x가 httpclient4.x와 다른가? – Felix

관련 문제