gpt4 book ai didi

java - 尝试创建一个Java程序来下载csv文件

转载 作者:行者123 更新时间:2023-12-01 11:07:50 25 4
gpt4 key购买 nike

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

}

}

关于java - 尝试创建一个Java程序来下载csv文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32736981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com