I am trying to upload a video with java to an api of Microsoft(Video Indexer API) using a request Http Post and it's work with Postman
But when i do this in java it's not work
This is my code :
public static void main(String[] args)
{
CloseableHttpClient httpclient = HttpClients.createDefault();
try
{
URIBuilder builder = new URIBuilder("https://videobreakdown.azure-api.net/Breakdowns/Api/Partner/Breakdowns?name=film2&privacy=Public");
URI uri = builder.build();
HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader("Content-Type", "multipart/form-data");
httpPost.setHeader("Ocp-Apim-Subscription-Key", "19b9d647b7e649b38ec9dbb472b6d668");
MultipartEntityBuilder multipart = MultipartEntityBuilder.create();
File f = new File("src/main/resources/film2.mov");
multipart.addBinaryBody("film2",new FileInputStream(f));
HttpEntity entityMultipart = multipart.build();
httpPost.setEntity(entityMultipart);
CloseableHttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null)
{
System.out.println(EntityUtils.toString(entity));
}
}
And this is the error:
{"ErrorType":"INVALID_INPUT","Message":"Content is not multipart."}
And for Postman this is a screen for all the parameter that i have to put on the Http Request
Screen for all the params on postman
And for the header:
header
Finally I found the problem
It was this line : httpPost.setHeader("Content-Type", "multipart/form-data");
I don't have to write that the Content-Type is multipart if I use a MultipartEntityBuilder ...
Try this solution definitely works
When you are using Postman for multipart request then don't specify a custom Content-Type in Header. So your Header tab in Postman should be empty. Postman will determine form-data boundary. In Body tab of Postman you should select form-data and select file type.
Related
I'm trying to publish image from my automation suite to slack channel.
URL to hit: https://slack.com/api/files.upload
Body is form-data type and it has,
file - image file upload
initial_comment - some string
channels - the slack channel to be published.
i tried using MultipartEntity class inside HttpPost
MultipartEntity multiPartEntity = new MultipartEntity();
FileBody fileBody = new FileBody(file);
//Prepare payload
multiPartEntity.addPart("file", fileBody);
multiPartEntity.addPart("file_type", new StringBody("JPG"));
multiPartEntity.addPart("initial_comment", new StringBody("cat shakes"));
multiPartEntity.addPart("channels", new StringBody("bot-e2e-report"));
//Set to request body
postRequest.setEntity(multiPartEntity);
Im getting the success response from http post. but the image is not posted in slack channel.any help!
The problem was with header. Actually, this slack api gives 200 response even for the wrong header. Working code:
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
//Set various attributes
MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();
entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entitybuilder.addBinaryBody("file", file);
entitybuilder.addTextBody("initial_comment", "cat");
entitybuilder.addTextBody("channels","bot-e2e-report");
HttpEntity mutiPartHttpEntity = entitybuilder.build();
RequestBuilder reqbuilder = RequestBuilder.post("https://slack.com/api/files.upload");
reqbuilder.setEntity(mutiPartHttpEntity);
//set Header
reqbuilder.addHeader("Authorization", "Bearer xoxb-16316687382-1220823299362-fdkBklPrY7rc72bQk3WSOSjD");
HttpUriRequest multipartRequest = reqbuilder.build();
// call post
HttpResponse response = httpclient.execute(multipartRequest);
// Parse the response
HttpEntity entity = response.getEntity();
String json = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println(json);
I am trying to do a POST request with 1 file object and 2 texts filed as below. But always getting 415 Unsupported Media Type. I'm using httpclient 4.4.
415 error is mean to mistake in body or header?
HttpPost request= new HttpPost("https://mysite/v1/files");
request.addHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");
request.addHeader("Authorization","Bearer <token>);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);`
File file = new File("/opt/productImages/productImage1.jpg");
builder.addTextBody("text", "productImage1.jpg", ContentType.TEXT_PLAIN);
builder.addTextBody("text", "productImage", ContentType.TEXT_PLAIN);
builder.addBinaryBody("upfile",uploadFile,ContentType.create("image/jpeg"),"productImage1.jpg");
HttpClient client = HttpClientBuilder.create().build();
HttpEntity entity = builder.build();
request.setEntity(entity);
HttpResponse response = client.execute(request);
System.out.println(response);
is there any way to debug it more to get the exact error.
I'm trying to use apache http components to interface with the Spotify api. The request I'm trying to send is detailed here under #1. When I send this request from bash using curl
curl -H "Authorization: Basic SOMETOKEN" -d grant_type=client_credentials https://accounts.spotify.com/api/token
I get back a token like the website describes
However the following java code, which as far as I can tell executes the same request, gives back a 400 error
Code
String encoded = "SOMETOKEN";
CloseableHttpResponse response = null;
try {
CloseableHttpClient client = HttpClients.createDefault();
URI auth = new URIBuilder()
.setScheme("https")
.setHost("accounts.spotify.com")
.setPath("/api/token")
.setParameter("grant_type", "client_credentials")
.build();
HttpPost post = new HttpPost(auth);
Header header = new BasicHeader("Authorization", "Basic " + encoded);
post.setHeader(header);
try {
response = client.execute(post);
response.getEntity().writeTo(System.out);
}
finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
}
Error
{"error":"server_error","error_description":"Unexpected status: 400"}
The URI that the code prints is looks like this
https://accounts.spotify.com/api/token?grant_type=client_credentials
And the header looks like this
Authorization: Basic SOMETOKEN
Am I not constructing the request correctly? Or am I missing something else?
Use form url-encoding for the data in the body with the content-type application/x-www-form-urlencoded :
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("https://accounts.spotify.com/api/token");
post.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoded);
StringEntity data = new StringEntity("grant_type=client_credentials");
post.setEntity(data);
HttpResponse response = client.execute(post);
I am using Spring as Technology. Apache HttpClient for calling Webservice. Basic purpose is to upload Multipart File(File is not any image file or video file). but Here My requirement is slightly different. Kindly check below image.
Here You can see first block. It is a simple GUI, having only 2 input tags along with proper form tag.
In second block, There is RESTFul Webservice, which takes Multipart File as parameter and process it. (Upto this it is done).
Now I am stuck here. I want to send this Multipart File to other RESTFul Webservice which consumes Multipart File only.
code Snippet of RESTFUL Webservice : (Commented some questions, need your suggestion)
#RequestMapping(value="/project/add")
public #ResponseBody String addURLListToQueue(
#RequestParam(value = "file") MultipartFile file,
#RequestParam(value = "id1", defaultValue = "notoken") String projectName,
#RequestParam(value = "id2", defaultValue = "notoken") String id2,
#RequestParam(value = "id3", defaultValue = "notoken") String id3){
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://localhost:8080/fs/project/add");
// 1) Do I need to convert it into File object? (tried but faced 400 Error)
// 2) Is there any provision to send Multipart File as it is?
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "multipart/form-data");
mpEntity.addPart("file", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
}
Questions : How to send Multipart File to RESTFul Webservice using HttpClient?
Can you check this file upload apache http client?
Also
HttpPost post = new HttpPost("http://echo.200please.com");
InputStream inputStream = new FileInputStream(zipFileName);
File file = new File(imageFileName);
String message = "This is a multipart post";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody
("upfile", file, ContentType.DEFAULT_BINARY, imageFileName);
builder.addBinaryBody
("upstream", inputStream, ContentType.create("application/zip"), zipFileName);
builder.addTextBody("text", message, ContentType.TEXT_PLAIN);
//
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
Source
I'm using the following code to send a http request to github.
String url = "https://api.github.com/repositories";
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(url);
// StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
// request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
System.out.println(json);
} catch (IOException ex) {
}
I got output: {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
If use directly put "https://api.github.com/repositories" in browser, a lot of useful information will be shown. My question is how can I get the information I see when using browser by using Java.
You should use HttpGet instead of HttpPost. Just like your browser sends a GET request.