Java 从服务器下载文件失败

Java 从服务器下载文件失败,java,http,httpclient,apache-commons-httpclient,Java,Http,Httpclient,Apache Commons Httpclient,现在我正试图从使用302的服务器下载一个文件,将get请求重定向到下载资源。当我使用下面的代码下载文件时,服务器响应失败,我想服务器知道我不使用brower下载文件。当我使用browser时,它工作正常,文件正确 你能告诉我代码中的问题在哪里吗?谢谢 这是我的代码: @SuppressWarnings("deprecation") public static void downloadFile(String url, String fileName, String page) throws In

现在我正试图从使用302的服务器下载一个文件,将get请求重定向到下载资源。当我使用下面的代码下载文件时,服务器响应失败,我想服务器知道我不使用brower下载文件。当我使用browser时,它工作正常,文件正确

你能告诉我代码中的问题在哪里吗?谢谢

这是我的代码:

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


org.apache.httpcomponents
httpclient
4.2.3

请查看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
注意:3xx范围内有许多响应代码,它们并不简单地表示要向其发送请求的不同URI。下面列出了这些响应代码,它们的处理方式将根据具体应用而定

当您的应用程序收到一个“简单”重定向响应时,它应该从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.
    }

一旦确定了新位置,就可以正常重新尝试连接。有关这方面的详细信息,请参阅教程。

是的,服务器使用302重定向我的请求,我认为问题发生在第二个请求中。但我不知道如何解决此问题,我将阅读此教程,谢谢。我认为httpclient不会自动重新定向请求(与浏览器不同)。文档建议您需要获取重定向位置并提出另一个请求。(我想:))httpClient.execute我只调用这个方法一次):httplient3.x是否与httpclient4.x不同?我不知道,根据文档,根据您使用的httpClient版本的服务器重定向数量,您需要多次调用它?
    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.
    }