尝试创建 Java 程序来下载 csv 文件

Trying to create a Java program to download a csv file

我创建了以下程序。它从给定的 URL 下载 html 代码。根据我在网上阅读的内容,我认为我需要添加 cookie 来解析用户凭据。只是想获得有关如何执行此操作的帮助。

非常感谢。

代码:

import java.io.*;
import java.net.URL;


public class DownloadDemo
{
    public static void main(String[] args)
    {
        StringBuilder contents = new StringBuilder(4096);
        BufferedReader br = null;

        try
        {
            String downloadSite = ((args.length > 0) ? args[0] : "https://www.google.co.uk/?gfe_rd=cr&ei=InoCVrPiCJDj8weWr57ABA");



            // file saved in your workspace
            String outputFile = ((args.length > 1) ? args[1] : "test.csv");
            URL url = new URL(downloadSite);
            InputStream is = url.openConnection().getInputStream();
            br = new BufferedReader(new InputStreamReader(is));
            PrintStream ps = new PrintStream(new FileOutputStream(outputFile));
            String line;
            String newline = System.getProperty("line.separator");
            while ((line = br.readLine()) != null)
            {
                contents.append(line).append(newline);
            }
            ps.println(contents.toString());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try { if (br != null) br.close(); } catch(IOException e) { e.printStackTrace(); }
        }
    }
}

这里有一个关于如何从 cookie 获取用户凭据的想法。

import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 

public class CookieTest extends HttpServlet 
{     
    public void doGet(HttpServletRequest req, HttpServletResponse res) 
    throws ServletException, IOException 
        { 
            res.setContentType("text/html"); 
            PrintWriter out = res.getWriter(); 

            //Get the current session ID by searching the received cookies. 
            String cookieid = null; 
            Cookie[] cookies = req.getCookies(); 

            if (cookies != null) 
            { 
                for (int i = 0; i < cookies.length; i++) 
                { 
                    if (cookies[i].getName().equals("REMOTE_USER")) 
                    { 
                         cookieid = cookies[i].getValue(); 
                         break; 
                    } 
                } 
            } 
            System.out.println("Cookie Id--"+cookieid); 

            //If the session ID wasn't sent, generate one. 
            //Then be sure to send it to the client with the response. 

        } 

}