Reputation: 419
I am trying to perform a HTTP Post Request in Java using the Apache API.
With curl the request looks like this
curl https://host/upload
-X POST
-H "Authorization: Bearer xxx"
-H "Content-Type: multipart/form-data"
-H "Accept: application/json"
-F "file=@{PathToImage}" -F "type=file"
While this work fine when running it with CURL the server returns a 500er result when running it with the following Java code
final HttpPost httppost = new HttpPost("https://host/upload");
httppost.addHeader("Authorization", "Bearer xxx");
httppost.addHeader("Accept", "application/json");
httppost.addHeader("Content-Type", "multipart/form-data");
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
final File file = new File("c:\\tmp\\myfile.pdf");
builder.addBinaryBody("file", file);
builder.addTextBody("type", "file");
final HttpEntity entity = builder.build();
httppost.setEntity(entity);
final HttpResponse response = httpclient.execute(httppost);
httpclient.close();
Any idea what I am missing here?
Upvotes: 4
Views: 8659
Reputation: 192
This question is similar. But I believe the answer is changing your addBinary to addPart.
final HttpPost httppost = new HttpPost("https://host/upload");
httppost.addHeader("Authorization", "Bearer xxx");
httppost.addHeader("Accept", "application/json");
httppost.addHeader("Content-Type", "multipart/form-data");
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
final File file = new File("c:\\tmp\\myfile.pdf");
builder.addPart("file", new FileBody(file));
builder.addTextBody("type", "file");
final HttpEntity entity = builder.build();
httppost.setEntity(entity);
final HttpResponse response = httpclient.execute(httppost);
httpclient.close();
Upvotes: 3
Reputation: 321
Try something like this instead
//import javax.net.ssl.HttpsURLConnection;
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
String encoding = Base64.getEncoder().encodeToString((user + ":" + psw).getBytes("UTF-8"));
con.setRequestProperty("Authorization", String.format("Basic %s", encoding));
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/xml; charset=UTF-8");
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Java client");
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(val);
Upvotes: 2
Reputation: 58774
Try syntax as baeldung multipart upload article suggest:
String textFileName = "c:\\tmp\\myfile.pdf";
final File file = new File(textFileName);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, textFileName);
builder.addTextBody("type", "file", ContentType.DEFAULT_BINARY);
create a multipart entity is to use the addBinaryBody and AddTextBody methods. These methods work for uploading text, files, character arrays, and InputStream objects.
Upvotes: 2