slack api : files to upload to slack channel - java

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

Related

Image File Upload 415 Unsupported Media Type Java Httpclient 4.4

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.

Post a video with multipart in java

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.

How to send JSON and audio MP3 file using HttpClient POST in Java

I am using HttpClient to send a request with JSON and MP3 audio content. Can anybody tell me where the below code goes wrong? I am using HttpClient version 4.5.2.
HttpClient httpClient = HttpClientBuilder.create().setUserAgent("MyAgent").setMaxConnPerRoute(4).build();
HttpPost httpPostRequest = new HttpPost("url");
httpPostRequest.addHeader("content-type","multipart/form-data");
File audioFile = new File("filename.mp3");
FileBody fileBody = new FileBody(audioFile);
StringBody jsonStringBody = new StringBody(gson.toJson(pojoObject).toString(), ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntityBuilder.setContentType(ContentType.MULTIPART_FORM_DATA);
multipartEntityBuilder.addPart("file", fileBody);
multipartEntityBuilder.addPart("jsonMetaData", jsonStringBody);
HttpEntity entity = multipartEntityBuilder.build();
httpPostRequest.setEntity(entity);
HttpResponse response = httpClient.execute(httpPostRequest);

Java : Send Multipart File to RESTWebservice

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

Creating a HTTP Server in Node.js service POST with file

I would like to order sent to the POST request with a parameter in the form of a JPG file.
I use HttpClient in version 4.4.1
Part of the Java code looks like this:
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
File file = new File("path_to_jpg");
HttpPost post = new HttpPost("http://localhost:1337/uploadJPG");
FileBody fileBody = new FileBody(file);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = httpclient.execute(post);
System.out.println(response.getEntity().getContent());
} finally {
httpclient.close();
}
next at "http://localhost:1337/uploadJPG" want to let nodeJS have a server that will process the JPG file
the idea of server code nodeJS:
var http = require('http'),
fs = require('fs'),
server = http.createServer( function(req, res) {
if (req.method == 'POST') {
//process file JPG
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('processed JPG');
}
});
port = 1337;
host = '127.0.0.1';
server.listen(1337, '127.0.0.1');
console.log('Listening at http://' + '127.0.0.1' + ':' + 1337);
and now my question is, How can I create such a service in NodeJS, which will have the file in jpg?
Not sure if you are using Express or not but if you are you can use a middleware like Multer which makes it very simple to handle MultiPart data and files.

Categories