我想要做的是从Java应用程序提交Web表单.我需要填写的表格位于:http://cando-dna-origami.org/
提交表单后,服务器会向给出的电子邮件地址发送一封确认电子邮件,目前我只是手工检查.我已经尝试手动填写表单,电子邮件也很好.(还应注意,当表单填写不正确时,页面只刷新并且不提供任何反馈).
我之前从未做过任何关于http的事情,但我环顾了一会儿,并提出了以下代码,它应该向服务器发送一个POST请求:
String data = "name=M+V&affiliation=Company&email="
+ URLEncoder.encode("m.v@gmail.com", "UTF-8")
+ "&axialRise=0.34&helixDiameter=2.25&axialStiffness=1100&bendingStiffness=230" +
"&torsionalStiffness=460&nickStiffness=0.01&resolution=course&jsonUpload="
+ URLEncoder.encode("C:/Users/Marjie/Downloads/twisted_DNA_bundles/monotwist.L1.v1.json",
"UTF-8") + "&type=square";
URL page = new URL("http://cando-dna-origami.org/");
HttpURLConnection con = (HttpURLConnection) page.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.connect();
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write(data);
out.flush();
System.out.println(con.getResponseCode());
System.out.println(con.getResponseMessage());
out.close();
con.disconnect();
Run Code Online (Sandbox Code Playgroud)
然而,当它运行时似乎没有做任何事情 - 也就是说,我没有收到任何电子邮件,虽然程序确实向System.out打印"200 OK",这似乎表明从服务器收到了一些东西虽然我不确定它究竟意味着什么.我认为问题可能出在文件上传中,因为我不确定该数据类型是否需要不同的格式.
这是使用Java发送POST请求的正确方法吗?我是否需要为文件上传执行不同的操作?谢谢!
在阅读了Adam的帖子之后,我使用了Apache HttpClient并编写了以下代码:
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("type", "square"));
//... add more parameters
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
HttpPost post = new HttpPost("http://cando-dna-origami.org/");
post.setEntity(entity);
HttpResponse response = …Run Code Online (Sandbox Code Playgroud)