如何用java发送post表单?

新手上路,请多包涵

我想在网站上发送一个带有 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>

原文由 Borut Flis 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 512
2 个回答

您可以编写与此类似的代码:

  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();
    }
  }
}

原文由 Satya 发布,翻译遵循 CC BY-SA 3.0 许可协议

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();

原文由 Aloong 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题