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

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

问题描述

我想要做的是从java应用程序提交一个web表单。我需要填写的表格位于: http://cando-dna-origami.org/



提交表单时,服务器会向给定的电子邮件地址发送确认电子邮件,现在我只需手动检查。我已经尝试手动填写表单,并且电子邮件发送得很好。 (还应该注意的是,当表单填写不正确时,页面会刷新并且不会给出任何反馈)。



我从来没有做过什么http之前,但我环顾了一下,并提出了下面的代码,它应该向服务器发送一个POST请求:

  String data =name = M + V& affiliation = Company& email =
+ URLEncoder.encode(mv@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;

网址页=新网址(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,这似乎表明从服务器收到了某些东西,尽管我不确定它是什么意思。我认为这个问题可能出现在文件上传中,因为我不确定该数据类型是否需要不同的格式。



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




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

 列表< NameValuePair> params = new ArrayList< NameValuePair>(); 
params.add(new BasicNameValuePair(type,square));
// ...添加更多参数

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请求,一个用表单,另一个用其他数据。我仍在寻找一种将这些结合为一个请求的方法;有没有人知道这件事?

解决方案

你可能会更好使用像 Apache HttpClient ,您可以通过它编程地构建 POST 请求。

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

列表< 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 改为:

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

httpost.setEntity(reqEntity);

他们的网站。 基于表单的登录和多部分编码的请求实体是很好的例子。



测试你的连接并查看底层网络数据来查看发生了什么。像 Firebug 这样的东西可以让你看到你的浏览器到底发生了什么,你可以打开HttpClient日志记录来查看所有交换的数据你的程序。或者,您可以使用Wireshark或Fiddler等实时查看您的网络流量。这可以让你更清楚地知道你的浏览器在做什么,而不是你的程序在做什么。


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).

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

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.

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


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

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?

解决方案

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

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.

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天全站免登陆