代码之家  ›  专栏  ›  技术社区  ›  user3837019

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

  •  0
  • user3837019  · 技术社区  · 9 年前

    我创建了以下程序。它从给定的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(); }
            }
        }
    }
    
    1 回复  |  直到 9 年前
        1
  •  1
  •   Sizons Joey    9 年前

    这里有一个关于如何从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. 
    
            } 
    
    }