Java 如何向Web服务器发送第二篇帖子?

Java 如何向Web服务器发送第二篇帖子?,java,html,cookies,protocols,httpurlconnection,Java,Html,Cookies,Protocols,Httpurlconnection,我有一个网站,我正在尝试登录并自动填写表格,最后发送数据。第一步是通过下面的代码实现的,即我可以登录,然后重定向到我想填写信息的页面 代码获取表单名称和值,并使用GET和POST对其进行更改,我想重复此过程,但这次使用多个表单(而不仅仅是用户名和密码)。我设法获取表单名称和值并更改HTML,但当我尝试将新值发布回服务器时,问题就出现了。我没有收到任何错误消息,代码返回新页面,但表单数据保持不变 我似乎在我的代码中找不到问题,第二个进程与第一个进程一样工作,唯一的区别是,我现在尝试将数据发布到多个

我有一个网站,我正在尝试登录并自动填写表格,最后发送数据。第一步是通过下面的代码实现的,即我可以登录,然后重定向到我想填写信息的页面

代码获取表单名称和值,并使用GET和POST对其进行更改,我想重复此过程,但这次使用多个表单(而不仅仅是用户名和密码)。我设法获取表单名称和值并更改HTML,但当我尝试将新值发布回服务器时,问题就出现了。我没有收到任何错误消息,代码返回新页面,但表单数据保持不变

我似乎在我的代码中找不到问题,第二个进程与第一个进程一样工作,唯一的区别是,我现在尝试将数据发布到多个表单

我认为问题在于我的
fillFormParams
sendPost
方法。谢谢你的帮助

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.net.HttpURLConnection;
public class HttpUrlConnectionExample {

  private List<String> cookies;
  private List<String> cookiejar;
  private static HttpURLConnection conn;


  private final String USER_AGENT = "Mozilla/5.0";

    public static void main(String[] args) throws Exception {

        String url = "http://www3.bagerisystem.se/webbordersodervidingebagarn/Logon.aspx";
        String menuPage = "http://www3.bagerisystem.se/webbordersodervidingebagarn/Meny.aspx";

        HttpUrlConnectionExample http = new HttpUrlConnectionExample();

        // make sure cookies is turn on
        http.createCookieManager();

        // 1. Send a "GET" request, so that you can extract the form's data.
        String page = http.GetPageContent(url);
        String postParams = http.getFormParams(page, "****", "****");

        // 2. Construct above post's content and then send a POST request for
        // authentication
        URL obj = new URL(url);
        conn = (HttpURLConnection) obj.openConnection();
        http.sendPost(url, postParams,conn);

        // 3. success then go to menuPage.
        String result = http.GetPageContent(menuPage);
        //System.out.println(result);

        // 4.Send new GET request
        String page2 = http.GetPageContent("http://www3.bagerisystem.se/webbordersodervidingebagarn/Retur.aspx");
        //System.out.println(page2);
        int[][] returVal = {   { 0, 1, 2, 3, 4, 5, 6, },{ 0, 1, 2, 3, 4, 5, 6, },{ 0, 1, 2, 3, 4, 5, 6, },{ 0, 1, 2, 3, 4, 5, 6, },{ 0, 1, 2, 3, 4, 5, 6, },{ 0, 1, 2, 3, 4, 5, 6, }};
        String postParams2 = http.fillFormParams(page2, returVal);
        // 5. Construct above post's content and then send a POST request for
        // authentication
        String url1 = "http://www3.bagerisystem.se/webbordersodervidingebagarn/Retur.aspx";
        URL obj1 = new URL(url1);
        conn = (HttpURLConnection) obj1.openConnection();
        http.sendPost(url1, postParams2,conn);
        // 6. success then go to menuPage.
        String resultz = http.GetPageContent("http://www3.bagerisystem.se/webbordersodervidingebagarn/Retur.aspx");
        System.out.println(resultz);
    }

  private void sendPost(String url, String postParams,HttpURLConnection conn) throws Exception {

    // Acts like a browser
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Host", "www3.bagerisystem.se");
    conn.setRequestProperty("User-Agent", USER_AGENT);
    conn.setRequestProperty("Accept",
        "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    for (String cookie : this.cookies) {
        conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
    }

    conn.setRequestProperty("Connection", "keep-alive");
    conn.setRequestProperty("Referer", "http://www3.bagerisystem.se/webbordersodervidingebagarn/Logon.aspx");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));

    conn.setDoOutput(true);
    conn.setDoInput(true);

    // Send post request
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(postParams);
    wr.flush();
    wr.close();

    int responseCode = conn.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + postParams);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = 
             new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
//   System.out.println(response.toString());

  }

  private String GetPageContent(String url) throws Exception {

    URL obj = new URL(url);
    conn = (HttpURLConnection) obj.openConnection();


    // default is GET
    conn.setRequestMethod("GET");

    conn.setUseCaches(false);

    // act like a browser
    conn.setRequestPropert`enter code here`y("User-Agent", USER_AGENT);
    conn.setRequestProperty("Accept",
        "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    if (cookies != null) {
        for (String cookie : this.cookies) {
            conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
        }
    }
    int responseCode = conn.getResponseCode();
//  System.out.println("\nSending 'GET' request to URL : " + url);
//  System.out.println("Response Code : " + responseCode);

    BufferedReader in = 
            new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    // Get the response cookies
    setCookies(conn.getHeaderFields().get("Set-Cookie"));

    return response.toString();

  }

  public String getFormParams(String html, String username, String password)

        throws UnsupportedEncodingException {

    //System.out.println("Extracting form's data...");

    Document doc = Jsoup.parse(html);

    //  form id
    Element loginform = doc.getElementById("Form1");
    Elements inputElements = loginform.getElementsByTag("input");
    List<String> paramList = new ArrayList<String>();
    for (Element inputElement : inputElements) {
        String key = inputElement.attr("name");
        String value = inputElement.attr("value");

        if (key.equals("UserNameTextBox"))//If corresponding input form is found, enter defined username
            value = username;
        else if (key.equals("PasswordTextBox"))//If corresponding input form is found, enter defined password
            value = password;
        paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
    }

    // build parameters list
    StringBuilder result = new StringBuilder();
    for (String param : paramList) {
        if (result.length() == 0) {
            result.append(param);
        } else {
            result.append("&" + param);
        }
    }
    return result.toString();
  }

  public List<String> getCookies() {
    return cookies;
  }

  public void setCookies(List<String> cookies) {
    this.cookies = cookies;
  }
  public void createCookieManager(){
      if (cookies == null) {
      CookieHandler.setDefault(new CookieManager());
      }
      }
  public String fillFormParams(String html, int[][] returVal) throws UnsupportedEncodingException{
      Document doc = Jsoup.parse(html);
      //Form id

      int row = 0;
      int column = 0;
      StringBuilder result = new StringBuilder();
      Element inputForm = doc.getElementById("Form1");
      Elements inputElements = inputForm.getElementsByTag("input");
      List<String> paramList = new ArrayList<String>();
      while(row <5 ){
      for (Element inputElement: inputElements){
          String key = inputElement.attr("name");
          String value = inputElement.attr("value");
          String truId =  "ReturDataGrid:_ctl" +(row+2);
        //  "ReturDataGrid%3A_ctl2%3AtxtAntal_1" + "=" + URLEncoder.encode("1", "UTF-8")
          String newId = truId + ":txtAntal_" + Integer.toString(column);
          if (column == 6) {
                 row++; 
                 column = (column+1)%7;
        }
          if(key.equals(newId)){
              key = "ReturDataGrid%3A_ctl"+(row+2) +"%3AtxtAntal_1" +column;
                value = Integer.toString(returVal[row][column]);
                 paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
            }    
      }
      column++;
      }
        for (String param : paramList) {
            if (result.length() == 0) {
                result.append(param);
            } else {
                result.append("&" + param);
            }
        }
        return result.toString();
  }
}
导入java.io.BufferedReader;
导入java.io.DataOutputStream;
导入java.io.InputStreamReader;
导入java.io.UnsupportedEncodingException;
导入java.net.CookieHandler;
导入java.net.CookieManager;
导入java.net.URL;
导入java.net.URLConnection;
导入java.net.urlcoder;
导入java.util.ArrayList;
导入java.util.List;
导入javax.net.ssl.HttpsURLConnection;
导入org.jsoup.jsoup;
导入org.jsoup.nodes.Document;
导入org.jsoup.nodes.Element;
导入org.jsoup.select.Elements;
导入java.net.HttpURLConnection;
公共类HttpUrlConnectionExample{
私有列表cookies;
私人名单cookiejar;
专用静态HttpURLConnection conn;
私有最终字符串用户_AGENT=“Mozilla/5.0”;
公共静态void main(字符串[]args)引发异常{
字符串url=”http://www3.bagerisystem.se/webbordersodervidingebagarn/Logon.aspx";
字符串菜单页=”http://www3.bagerisystem.se/webbordersodervidingebagarn/Meny.aspx";
HttpUrlConnectionExample http=新的HttpUrlConnectionExample();
//确保cookies已打开
http.createCookieManager();
//1.发送“获取”请求,以便提取表单数据。
String page=http.GetPageContent(url);
字符串postParams=http.getFormParams(第页“****”、“****”);
//2.构建上述帖子的内容,然后发送帖子请求
//认证
URL obj=新URL(URL);
conn=(HttpURLConnection)obj.openConnection();
sendPost(url,postParams,conn);
//3.成功然后进入菜单页。
字符串结果=http.GetPageContent(menuPage);
//系统输出打印项次(结果);
//4.发送新的GET请求
字符串page2=http.GetPageContent(“http://www3.bagerisystem.se/webbordersodervidingebagarn/Retur.aspx");
//系统输出打印项次(第2页);
int[]returVal={0,1,2,3,4,5,6,},{0,1,2,3,4,5,6,},{0,1,2,3,4,5,6,},{0,1,2,3,3,4,4,5,6,},{0,1,2,4,5,6,},{0,1,2,3,4,5,6,};
字符串postParams2=http.fillFormParams(第2页,returVal);
//5.构建上述帖子的内容,然后发送帖子请求
//认证
字符串url1=”http://www3.bagerisystem.se/webbordersodervidingebagarn/Retur.aspx";
URL obj1=新URL(url1);
conn=(HttpURLConnection)obj1.openConnection();
http.sendPost(url1,postParams2,conn);
//6.成功然后进入菜单页。
字符串resultz=http.GetPageContent(“http://www3.bagerisystem.se/webbordersodervidingebagarn/Retur.aspx");
System.out.println(resultz);
}
私有void sendPost(字符串url、字符串postParams、HttpURLConnection conn)引发异常{
//就像一个浏览器
conn.SETUSECHACHES(假);
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“主机”,“www3.bagerisystem.se”);
conn.setRequestProperty(“用户代理”,用户代理);
conn.setRequestProperty(“接受”,
“text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8”);
conn.setRequestProperty(“接受语言”,“en-US,en;q=0.5”);
for(字符串cookie:this.cookies){
conn.addRequestProperty(“Cookie”,Cookie.split(“;”,1)[0]);
}
conn.setRequestProperty(“连接”、“保持活动”);
conn.setRequestProperty(“Referer”http://www3.bagerisystem.se/webbordersodervidingebagarn/Logon.aspx");
conn.setRequestProperty(“内容类型”、“应用程序/x-www-form-urlencoded”);
conn.setRequestProperty(“内容长度”,Integer.toString(postParams.Length());
连接设置输出(真);
conn.setDoInput(真);
//发送邮寄请求
DataOutputStream wr=新的DataOutputStream(conn.getOutputStream());
wr.writeBytes(后参数);
wr.flush();
wr.close();
int responseCode=conn.getResponseCode();
System.out.println(“\n向URL发送'POST'请求:“+URL”);
System.out.println(“Post参数:“+postParams”);
System.out.println(“响应代码:“+responseCode”);
BufferedReader in=
新的BufferedReader(新的InputStreamReader(conn.getInputStream());
字符串输入线;
StringBuffer响应=新的StringBuffer();
而((inputLine=in.readLine())!=null){
追加(inputLine);
}
in.close();
//System.out.println(response.toString());
}
私有字符串GetPageContent(字符串url)引发异常{
URL obj=新URL(URL);
conn=(HttpURLConnection)obj.openConnection();
//默认值是GET
conn.setRequestMethod(“GET”);
conn.SETUSECHACHES(假);
//像一个浏览器
conn.setRequestPropert`在此处输入代码`y(“用户代理”,用户代理);
conn.setRequestProperty(“接受”,
“text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8”);
conn.setRequestProperty(“接受语言”,“en-US,en;q=0.5”);
如果(cookies!=null){
for(字符串cookie:this.cookies){
C