简体   繁体   English

如何在Java中使用httprequest发送文件?

[英]how to send file with httprequest in java?

how to send file with http request in java ? 如何在Java中使用http请求发送文件? i see question Send image file using java HTTP POST connections and Upload files from Java client to a HTTP server but them are too old question and not work any more . 我看到了使用Java HTTP POST连接发送图像文件和将文件从Java客户端上传到HTTP服务器的问题,但是它们太旧了,无法再使用了。

A good example is given in Multi part File Upload example of Apache HttpClient Apache HttpClient的多部分文件上传示例中给出了一个很好的示例

http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/MultipartFileUploadApp.java?view=markup http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/MultipartFileUploadApp.java?view=markup

The part that actually posts the file is 实际发布文件的部分是

            String targetURL = cmbURL.getSelectedItem().toString();
            // add the URL to the combo model if it's not already there
            if (!targetURL
                .equals(
                    cmbURLModel.getElementAt(
                        cmbURL.getSelectedIndex()))) {
                cmbURLModel.addElement(targetURL);
            }

            PostMethod filePost = new PostMethod(targetURL);

            filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE,
            cbxExpectHeader.isSelected());
            try {
                appendMessage("Uploading " + targetFile.getName() + " to " + targetURL);
                Part[] parts = {
                    new FilePart(targetFile.getName(), targetFile)
                };
                filePost.setRequestEntity(
                    new MultipartRequestEntity(parts, filePost.getParams())
                    );
                HttpClient client = new HttpClient();
                client.getHttpConnectionManager().
                    getParams().setConnectionTimeout(5000);
                int status = client.executeMethod(filePost);
                if (status == HttpStatus.SC_OK) {
                    appendMessage(
                        "Upload complete, response=" + filePost.getResponseBodyAsString()
                    );
                } else {
                    appendMessage(
                        "Upload failed, response=" + HttpStatus.getStatusText(status)
                    );
                }
            } catch (Exception ex) {
                appendMessage("ERROR: " + ex.getClass().getName() + " "+ ex.getMessage());
                ex.printStackTrace();
            } finally {
                filePost.releaseConnection();
            }

Hope it is of some help to you. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM