how to send file with http request in java ? 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 .
Asked
Active
Viewed 531 times
0
-
Why not? What happens? – SLaks Sep 18 '15 at 16:16
-
you may consider my [http client](http://bayou.io/release/0.9/docs/http/Http_Client.html#Form_Submission) – ZhongYu Sep 18 '15 at 16:41
-
amount of class is deprecated – mohammad amin Sep 18 '15 at 17:25
-
i need simple method that that give URL target and File then send it . – mohammad amin Sep 18 '15 at 20:12
1 Answers
3
A good example is given in Multi part File Upload example of Apache HttpClient
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.

Thomas Ramapuram
- 46
- 3
-
i write my program in console . this not work for me . please simple this if you can – mohammad amin Sep 18 '15 at 20:07
-
-
if you are familiar with github I have uploaded a sample project to post files. This project uses httpclient 4.3.6 so the code is slightly diffrent from the above code.[HttpPostExample](https://github.com/thomasramapuram/httpPostTest) – Thomas Ramapuram Sep 25 '15 at 10:25