gpt4 book ai didi

java - 如何在java中使用http请求发送文件?

转载 作者:行者123 更新时间:2023-12-01 22:06:36 29 4
gpt4 key购买 nike

如何在java中使用http请求发送文件?我看到问题 Send image file using java HTTP POST connectionsUpload files from Java client to a HTTP server但它们太老了,不再起作用了。

最佳答案

Apache HttpClient 的分段文件上传示例中给出了一个很好的示例

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

实际发布文件的部分是

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

希望对您有帮助。

关于java - 如何在java中使用http请求发送文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32656611/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com