如何使用java发送帖子表单?

2022-09-02 09:44:04

我想在网站上发送带有java的帖子表单。我想出了这个,但我不知道下一步该做什么,或者这是否是正确的方法。

URL url = new URL("http://127.0.0.1");
URLConnection conn=url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);

帖子表单如下所示。

<form action="prikaz4.php" method="post">
    <select name="igralec"/>
    <option value="Kobe Bryant">Kobe Bryant</option>
    <option value="Dwayne Wade">Dwayne Wade</option>
    <input type="submit" />
</form>

答案 1

你可以编写类似这样的代码:

 import org.apache.commons.httpclient.HttpClient;
 import org.apache.commons.httpclient.HttpException;
 import org.apache.commons.httpclient.HttpStatus;
 import org.apache.commons.httpclient.methods.PostMethod;
 import org.apache.http.impl.client.HttpClients;

public class PostReqEx {

  public void sendReq(String url,String email,String fname){
    HttpClient httpClient = HttpClients.createDefault();
    PostMethod postMethod = new PostMethod(url);
    postMethod.addParameter("Email", email);
    postMethod.addParameter("fname", fname);
    try {
        httpClient.executeMethod(postMethod);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
        String resp = postMethod.getResponseBodyAsString();
    } else {
         //...postMethod.getStatusLine();
    }
  }
}

答案 2

Apache的HttpClient项目将更好地为您处理这个问题。

或者你可以试试这个代码:

// Using java.net.URL and  
    //java.net.URLConnection  
    URL url = new URL("http://jobsearch.dice.com/jobsearch/jobsearch.cgi");   
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);  
    OutputStreamWriter out = new OutputStreamWriter(uc.getOutputStream(), "8859_1");   
    out.write("username=bob&password="+password+"");   
    // remember to clean up   
    out.flush();   
    out.close();