javascript - 在 Java 中使用 HTTPClient 下载文件

标签 javascript java apache-httpclient-4.x

我正在尝试编写一个java程序,该程序登录到网站,输入搜索引擎,获取结果,然后下载从结果生成的excel文件。到目前为止,我可以正常登录。并发送搜索并获取结果。但是,我在下载 Excel 文件时遇到很多问题。

查看网站的源代码,我看到 Excel 文件周围有 Ajax 和 Javascript,因此我假设是 ajax 帮助生成了它。

<input id="toexcel" type="image" src="/websmart/v9.4/XLGP/images/Excel-icon.png" alt="To Excel" title="To Excel: Max 20000 Records" onclick="" />

JavaScript 部分:

$( document ).ready(function() {

        $('#toexcel').click(function(e) { 
            e.preventDefault();
            
            setTask('toexcel');
            
            var ajaxForm = $("#filter-form");
                        
            
            $(".spinner").show();

                var dataToSend = ajaxForm.serialize();
                $("#excelFrame").attr('src','V7BAE01R.pgm' + '?' + dataToSend);
            setTimeout(function() {
                            $(".spinner").hide();
                        }, 5000 );
                

使用 TamperData,当我单击 Excel 文件导出时,它会发送一个发布请求(我设法在代码的最后部分发送),但我不确定从哪里获取它。我确实在 tamperdata 中看到了显示 Application/vnd.ms-excel

的 Get

enter image description here

我不知道如何添加代码来获取 Excel 文件。下面,我尝试使用 BufferReader,但它没有获取我的文件。由于名称值对,我简化了一些代码。

import java.util.List;
import java.util.ArrayList;
import org.apache.http.*;
import java.io.*;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import org.apache.http.message.*;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.entity.*;
public class httpClientTest {
    
    
    
    public static void main (String[] args) throws ClientProtocolException, IOException {
            //Set up HttpClient
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet("http://website");
            CloseableHttpResponse response = httpclient.execute(httpGet);
            
            //Create Post request to log into the AS400 website
            HttpPost httpPost = new HttpPost("http://loginwebsite");
            
            List <NameValuePair> nvps = new ArrayList <NameValuePair>();
            
            nvps.add(new BasicNameValuePair("user","username"));
            nvps.add(new BasicNameValuePair("password","password"));
            nvps.add(new BasicNameValuePair("button", "Login"));
            nvps.add(new BasicNameValuePair("task", "extlogin"));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            response = httpclient.execute(httpPost);
            
            //Get Post response to ensure we logged in, which succeeds
            try{
                System.out.println(response.getStatusLine());   
                HttpEntity entity = response.getEntity();
                EntityUtils.consume(entity);
            } finally{
                response.close();
            }
            
            //Sent a Post request to filters out recoreds.
            httpPost = new HttpPost("http://searchresults");
            nvps.clear();
            nvps.add(new BasicNameValuePair("ActSts", "Edit"));
            nvps.add(new BasicNameValuePair("task", "filter"));
            nvps.add(new BasicNameValuePair("Field", "Plant"));
            response = httpclient.execute(httpPost);
            
            //Displays in printline the html/js of the page. This looks like it DOES display the search results
            //So it IS sending the Post request and receiving a response.
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
            String line = "";
            while ((line = rd.readLine()) != null) {
                System.out.println(line);
            }

        //try to buffer to read in.
        String link = "http://website.com/uri?ActSts=Edit&task=filter&Field=Plant";
        HttpGet get = new HttpGet(link);
        response = httpclient.execute(get);
        
        InputStream is = response.getEntity().getContent();
        String filePath = "C:\\Users\\WindowsUserName\\Downloads\\WODETAIL_List.xls";
        FileOutputStream fos = new FileOutputStream(new File(filePath));
        int inByte;
        while((inByte = is.read()) != -1)
            fos.write(inByte);
        is.close();
        fos.close();

我很确定我正确发布了数据,但我不确定如何获取 Excel 文件。有人可以提供一些帮助吗?

编辑 我能够下载文件,但它不是 Excel 文件。这是一个网页,我认为这是一个小小的改进。 (之前,没有下载任何内容,它只是卡在那里)问题是,我想我需要使用此 get 请求发送授权 key 或 cookie 来下载文件。

编辑 2 我发现如果我只是粘贴到 http://website.com/uri?ActSts=Edit&task=filter&Field=Plant登录后在新选项卡中,稍等片刻后,我得到了 Excel 文件的链接。所以最初我认为只要使用相同的 httpclient,HTTPClient 就会始终维护相同的 cookie,但显然它不会(?)我想我必须找到一种方法来获取 cookie 并发送它。

最佳答案

天哪,我终于得到了有用的东西。好的。因此显然 HTTPClient 在开始出错之前只能处理 2 个响应,根据这里:Why does me use HttpClients.createDefault() as HttpClient singleton instance execute third request always hang

因此,我将代码更改为仅获取登录响应,然后获取 excel 文件作为响应,然后退出。我还添加了一些超时配置,并更改了先导出文件然后使用实体的顺序。我使用了单独的第二响应和第二实体。这似乎也有一点帮助?我猜。

import java.util.List;
import java.util.ArrayList;
import org.apache.http.*;
import java.io.*;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.*;
import org.apache.http.message.*;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.entity.*;

public class hcFeb {
    public static void main (String[] args) throws ClientProtocolException, IOException {
        //Set up Cookie settings and also Timeout settings
        CookieStore cookieStore = new BasicCookieStore();
        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookieStore);
        
        int CONNECTION_TIMEOUT = 80000;
        RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT)
                .setConnectionRequestTimeout(CONNECTION_TIMEOUT)
                .setConnectTimeout(CONNECTION_TIMEOUT)
                .setSocketTimeout(CONNECTION_TIMEOUT)
                .build();
        
        //Set up HttpClient
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).setDefaultCookieStore(cookieStore).disableContentCompression().build();
        
        HttpGet httpGet = new HttpGet("http://website");
        CloseableHttpResponse response = httpclient.execute(httpGet);
        
        //Create Post request to log into the website
        HttpPost httpPost = new HttpPost("http://loginwebsite");
        
        //Login to website
         List <NameValuePair> nvps = new ArrayList <NameValuePair>();

            nvps.add(new BasicNameValuePair("user","username"));
            nvps.add(new BasicNameValuePair("password","password"));
            nvps.add(new BasicNameValuePair("button", "Login"));
            nvps.add(new BasicNameValuePair("task", "extlogin"));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            response = httpclient.execute(httpPost);

        
        try{
            System.out.println(response.getStatusLine());   
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);                
        } finally{
        }
        
        //Send request for Excel file and download it.
        String link = "http://website.com/uri?ActSts=Edit&task=filter&Field=Plant";
        HttpGet get = new HttpGet(link);
        
        //maybe create new response
        HttpResponse response2;

        try{
            response2 = httpclient.execute(get,context);
            System.out.println(response2.getStatusLine());  
            HttpEntity entity1 = response2.getEntity();


            if (entity1 != null) {
                System.out.println("Entity isn't null");
                
                InputStream is = entity1.getContent();
                String filePath = "C:\\Users\\windowsUserName\\Downloads\\WODETAIL_List.xls";
                FileOutputStream fos = new FileOutputStream(new File(filePath));
                
                byte[] buffer = new byte[5600];
                int inByte;
                while((inByte = is.read(buffer)) > 0)
                    fos.write(buffer,0,inByte);
                is.close();
                fos.close();
                
                System.out.println("Excel File recieved");                  
                
                
                EntityUtils.toString(response2.getEntity());
                EntityUtils.consume(entity1);
                
            }
            
        } catch (ConnectionPoolTimeoutException e){
            //response.close();
            System.out.println(e.getMessage());
        } catch (IOException e){
            System.out.println(e.getMessage());
        }
        
    }
}

关于javascript - 在 Java 中使用 HTTPClient 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35438281/

相关文章:

java - JSON: "Unexpected character (<) at position 0"

java - 在fuse Fabric中部署camel项目

java - Jetty 支持来自 SoapUI 的 TLS 1.2 请求

javascript - Jquery 延迟停止代码,就像警告框一样

javascript - 当我点击另一个功能时,如何使按钮点击事件发生?

java - 在 Java Portlet 中获取用户角色

java - Apache DefaultHttpClient : How to set max. 总连接数和默认最大值。每条路线的连接数

java - 如何使内容类型为 : application/json in the apache httpPost method

javascript - 第一次在对象内调用时,JS 对象属性未定义

javascript - 为什么堆栈跟踪在 .ts 文件中的一行中显示 3 个调用