有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java连接到需要用户/密码的web

我对Java有点陌生,更不熟悉它的连接。我正在尝试创建一个程序来连接到一个网站(“www.buybackprofessional.com”),在那里我想下载图片并从汽车中获取一些文本(登录后,您必须输入车牌号才能访问汽车文件)

这就是我现在拥有的,但它总是说会话已经过期,我需要一种使用主页的用户名和密码登录的方式,对吗?有人能给我一些建议吗?谢谢

注意:我想用Java来做,也许我不清楚这个问题

        //URL web = new URL("http://www.buybackprofesional.com/DetallePeri.asp?mat=9073FCV&fec=27/07/2010&tipo=C&modelo=4582&Foto=0");
        URL web = new URL("http://www.buybackprofesional.com/");
        HttpURLConnection con = (HttpURLConnection) web.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; JVM)");
        con.setRequestProperty("Pragma", "no-cache");
        con.connect();
              BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }                  

一位同事帮了我这个忙,所以我将发布有效的代码:

public static URLConnection login(String _url, String _username, String _password) throws IOException, MalformedURLException {

    String data = URLEncoder.encode("Usuario", "UTF-8") + "=" + URLEncoder.encode(_username, "UTF-8");
    data += "&" + URLEncoder.encode("Contrase", "UTF-8") + "=" + URLEncoder.encode(_password, "UTF-8");

    // Send data
    URL url = new URL(_url);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();
    wr.close();
    return conn;
}

这将提交我需要的页面上的表单信息,之后,使用cookies我可以保持连接


共 (1) 个答案

  1. # 1 楼答案

    使用j{a1}或httpcore(由Apache提供)使用java连接到网站。他们处理会话的能力比你(或我)自己做的要好得多

    编辑:修复链接的位置。谢谢你的更正