我想做的是从
java应用程序提交一个Web表单.我需要填写的表格位于:
http://cando-dna-origami.org/
提交表单时,服务器会向给定的电子邮件地址发送确认电子邮件,现在我只需手动检查.我已经尝试手动填写表单,电子邮件发送正常. (还应该注意的是,当表单填写不正确时,页面只是刷新,没有给出任何反馈).
我以前从来没有做过任何事情,但是我环顾了一段时间,并提出了以下代码,它应该向服务器发送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();
但是,当它运行它似乎没有做任何事情 – 也就是说,我没有收到任何电子邮件,虽然该程序打印“200 OK”到System.out,这似乎表明从服务器收到的东西,虽然我不知道这是什么意思.我认为问题可能在文件上传,因为我不知道这种数据类型是否需要不同的格式.
这是使用Java发送POST请求的正确方法吗?我需要为文件上传做不同的事情吗?谢谢!
阅读Adam的帖子后,我使用Apache HttpClient并写了以下代码:
List params = new ArrayList();
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 = new DefaultHttpClient().execute(post);
post = new HttpPost("http://cando-dna-origami.org/");
post.setEntity(new FileEntity(new File("C:/Users/Marjie/Downloads/twisted_DNA_bundles/monotwist.L1.v1.json"), "text/plain; charset=\"UTF-8\""));
HttpResponse responseTwo = new DefaultHttpClient().execute(post);
但是,它似乎还没有起作用;再次,我不知道上传的文件如何适应表单,所以我尝试只发送两个单独的POST请求,一个与表单,一个与其他数据.我仍然在寻找一种将这些组合成一个请求的方法;有人知道这件事吗?