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

时间:2015-09-23 10:21:34

标签: java cookies credentials

我创建了以下程序。它从给定的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 个答案:

答案 0 :(得分:1)

以下是关于如何从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. 

        } 

}