Java 中的 Http POST(带文件上传) [英] Http POST in Java (with file upload)

查看:126
本文介绍了Java 中的 Http POST(带文件上传)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是从 Java 应用程序提交 Web 表单.我需要填写的表格在这里:http://cando-dna-origami.org/

What I want to do is submit a web form from a java application. The form I need to fill out is located here: http://cando-dna-origami.org/

提交表单后,服务器会向给定的电子邮件地址发送一封确认电子邮件,目前我只是手动检查.我试过手动填写表格,邮件发送正常.(还需要注意的是,当表单填写不正确时,页面只是刷新,不提供任何反馈).

When the form is submitted, the server sends a confirmation email to the email address given, which for now I'm just checking by hand. I've tried filling out the form manually, and the emails get sent fine. (It should also be noted that when the form is filled out incorrectly, the page just refreshes and doesn't give any feedback).

我之前从未对http做过任何事情,但是我环顾四周,得出了以下代码,该代码应该向服务器发送POST请求:

I've never done anything with http before, but I looked around for a while, and came up with the following code, which is supposed to send a POST request to the server:

    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",这似乎表明收到了一些东西来自服务器,虽然我不确定它的确切含义.我认为问题可能出在文件上传上,因为我不确定该数据类型是否需要不同的格式.

However, when it runs it doesn't appear to do anything - that is, I don't get any emails, although the program does print "200 OK" to System.out, which seems to indicate that something got received from the server, although I'm not sure what it means exactly. I think the problem might be in the file uploading, since I wasn't sure whether that data type required a different format.

这是使用 Java 发送 POST 请求的正确方法吗?我需要为文件上传做一些不同的事情吗?谢谢!

Is this a correct way to send a POST request using Java? Do I need to do something different for the file uploading? Thanks!

阅读了 Adam 的帖子后,我使用了 Apache HttpClient 并编写了以下代码:

After reading Adam's post, I used Apache HttpClient and wrote the following code:

    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 请求,一个带有表单,一个带有其他数据.我仍在寻找一种将这些组合成一个请求的方法;有人知道这件事吗?

However, it still doesn't seem to be working; again, I wasn't sure how the uploaded file fit into the form, so I tried just sending two separate POST requests, one with the form and one with the other data. I am still looking for a way to combine these into one request; does anybody know something about this?

推荐答案

使用 Apache HttpClient 之类的东西可能会更好,您可以使用它以编程方式构建 POST 请求.

You would probably be better off using something like Apache HttpClient, with which you can build up a POST request programatically.

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://.../whatever");

List <NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("param2", "value2"));
...

httpost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

HttpResponse response = httpclient.execute(httppost);

如果您需要随表单一起上传文件,则需要使用 MultipartEntity 代替:

If you need to upload a file along with your form, you will need to use a MultipartEntity instead:

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("someParam", "someValue");
reqEntity.addPart("someFile", new FileBody("/some/file"));
....

httpost.setEntity(reqEntity);

他们的网站上有一些示例程序.基于表单的登录"和多部分编码的请求实体"是很好的例子.

There are some sample programs over on their site. The "Form based logon" and "Multipart encoded request entity" are good examples to start from.

测试您的连接并查看底层网络数据以了解正在发生的情况也可能是值得的.像 Firebug 之类的东西可以让你确切地看到浏览器中发生的事情,你可以打开 HttpClient 日志来查看所有交换的数据你的程序.或者,您可以使用 Wireshark 或 Fiddler 之类的工具来实时查看您的网络流量.这可能会让您更清楚地了解浏览器在做什么,而不是您的程序在做什么.

It may also be worthwhile testing out your connections and taking a look at the underlying network data to see what is happening. Something like Firebug will let you see exactly what is happening in your browser, and you can turn up the HttpClient logging to see all of the data exchanged in your program. Alternatively, you can use something like Wireshark or Fiddler to watch your network traffic in real-time. This may give you a better idea of exactly what your browser is doing, versus what your program is doing.

这篇关于Java 中的 Http POST(带文件上传)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆