Http POST in Java (with file upload)

前端 未结 5 1118
野的像风
野的像风 2020-12-14 03:33

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 submitte

5条回答
  •  感情败类
    2020-12-14 03:48

    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  params = new ArrayList();
    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.

提交回复
热议问题