简体   繁体   English

从服务器下载文件失败

[英]download file from server failed

Now I am trying to download a file from the server which use 302 redirect the get request to the download resourse.Well when I use my code below to download file the server reponse with failed I think the server knows I don`t use brower to download file.When I use browser it works fine and the file is right. 现在我正在尝试从服务器上下载文件,该服务器使用302将get请求重定向到下载资源。当我使用下面的代码下载文件时,服务器响应失败我认为服务器知道我不使用浏览器下载文件。当我使用浏览器时,它工作正常,文件正确。

Can you tell me where is the problem in my code.thanks. 您能告诉我代码中的问题在哪里吗?谢谢。

this is my code: 这是我的代码:

@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: pom:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.2.3</version>
</dependency>

Please have a look at the http documentation http://hc.apache.org/httpclient-legacy/redirects.html I think you need to handle redirection manually 请查看http文档http://hc.apache.org/httpclient-legacy/redirects.html我认为您需要手动处理重定向

Handling redirects manually 手动处理重定向

All response codes between 300 and 399 inclusive are redirect responses of some form. 在300到399(含)之间的所有响应代码都是某种形式的重定向响应。 The most common redirect response codes are: 最常见的重定向响应代码为:

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

Note: there are a number of response codes in the 3xx range which do not simply indicate a different URI to send the request to. 注意:3xx范围内有许多响应代码,它们不仅仅指示将请求发送到的其他URI。 These response codes are listed below and the manner they are handled will be application specific. 这些响应代码在下面列出,其处理方式将取决于特定应用。

When your application receives one of the "simple" redirect responses, it should extract the new URL from the HttpMethod object and retry downloading from that URL. 当您的应用程序收到“简单”重定向响应之一时,它应从HttpMethod对象中提取新URL,然后重试从该URL下载。 Additionally, it is usually a good idea to limit the number of redirects that will be followed in case the redirects form a recursive loop. 另外,在重定向形成递归循环的情况下,限制重定向的数量通常是一个好主意。

The URL to connect to can be extracted from the Location header. 可以从Location标头中提取要连接的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.
    }

Once you have determined the new location, you can reattempt the connection as normal. 确定新位置后,您可以照常尝试重新尝试连接。 See the Tutorial for more information on this. 有关更多信息,请参见教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM