我有一个网站,我尝试登录并自动填写表格,然后最终发送数据。第一步是使用下面的代码实现的,即我可以登录然后重定向到我希望填写信息的页面。
代码获取表单名称和值,并使用GET和POST更改它们,我想重复此过程,但这次使用多个表单(而不仅仅是用户名和密码)。我设法获取表单名称和值并更改HTML,但是当我尝试将新值发回服务器时会出现问题。我没有收到任何错误消息,代码返回新页面但表单数据保持不变。
我似乎无法在我的代码中找到问题,第二个过程就像第一个过程一样,唯一的区别是,我现在尝试将POSTdata转换为多个表单。
我认为问题在于我的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();
}
}