[英]Passing data to an html POST form using Java
我有一個HTML表單,看起來像這樣:
<form name="form1" method="post" action="/confirm.asp">
<input type="text" name="data1" size="20" value=""><br>
<input type="text" name="data2" size="20" value=""><br>
<input type="Submit" name=submit value="Submit">
</form>
我想使用Java將數據傳遞給data1
和data2
並在提交表單時讀取data2
的頁面。 由於這是一個方法=帖子,我不能使用http://somesite.com/confirm.asp?data1=foo&data2=foo
。
可以幫忙嗎?
/* create a new URL and open a connection */
URL url = new URL("http://somesite.com/confirm.asp");
URLConnection con = url.openConnection();
con.setDoOutput(true);
/* wrapper the output stream of the connection with PrintWiter so that we can write plain text to the stream */
PrintWriter wr = new PrintWriter(con.getOutputStream(), true);
/* set up the parameters into a string and send it via the output stream */
StringBuilder parameters = new StringBuilder();
parameters.append("data1=" + URLEncoder.encode("value1", "UTF-8"));
parameters.append("&");
parameters.append("data2=" + URLEncoder.encode("value2", "UTF-8"));
wr.println(parameters);
wr.close();
/* wrapper the input stream of the connection with BufferedReader to read plain text, and print the response to the console */
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while((line = br.readLine()) != null) System.out.println(line);
br.close();
這是Link的代碼。 希望這可以幫助你:)
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostForm
{
public static void main(String[] args)
{
try
{
URL url = new URL( "http://www.aaaa.com/xyz.asp" );
HttpURLConnection hConnection = (HttpURLConnection)
url.openConnection();
HttpURLConnection.setFollowRedirects( true );
hConnection.setDoOutput( true );
hConnection.setRequestMethod("POST");
PrintStream ps = new PrintStream( hConnection.getOutputStream() );
ps.print("param1=abcd&param2=10341");
ps.close();
hConnection.connect();
if( HttpURLConnection.HTTP_OK == hConnection.getResponseCode() )
{
InputStream is = hConnection.getInputStream();
OutputStream os = new FileOutputStream("output.html");
int data;
while((data=is.read()) != -1)
{
os.write(data);
}
is.close();
os.close();
hConnection.disconnect();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
要用Java編寫POST請求,您應該通過URLConnection連接到目標URL,然后在其中寫入頭邊界的字節,邊界消息(放置鍵,值和任何其他請求數據的位置),以及結束邊界。
我為我的應用程序編寫了一個PostProcess類,它允許異步POST請求上傳,鍵值參數,文件參數(即表單中的文件上傳輸入)和上傳進度跟蹤。 它還記錄服務器響應。
為了大小和可讀性,我已將代碼外部上傳到http://textu.be/T
請嘗試以下代碼
String url="www.somesite.com";
Document doc = Jsoup.connect(url).data("data1", "foo").data("data2","foo")
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com").post();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.