【发布时间】:2012-03-13 21:05:55
【问题描述】:
我想做的是从 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();
但是,当它运行时,它似乎没有做任何事情——也就是说,我没有收到任何电子邮件,尽管程序确实向 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 = 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 请求,一个带有表单,一个带有其他数据。我仍在寻找一种将这些组合成一个请求的方法;有人知道吗?
【问题讨论】: