I'm using org.apache.http.* and trying to PUT a file. I can do it with the below reference to the actual file, however, I'm looking for a way to do it by passing in an InputStream
File file = new File("/mytestfile.txt")
HttpPut request = new HttpPut("http://sharepointportal/site/mytestfile.txt");
request.setEntity(new FileEntity(file));
CloseableHttpResponse response = httpclient.execute(new HttpHost("sharepointportal"), request);
FileEntity doesn't seem to have a constructor that supports InputStream.
Question
How can I setEntity for HttpPut request with an InputStream?
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);
Following is my curl request:
curl -X POST --data-urlencode 'data1#/Users/Documents/file.csv' http://localhost:8000/predict
Following is my equivalent Java implementation.
String filePath = inputFilePath;
String url = inputUrl;
File file = new File(filePath);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost(inputUrl);
uploadFile.addHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
FileBody fileBody = new FileBody(new File(inputFilePath));
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("data1", fileBody)
.build();
uploadFile.setEntity(reqEntity);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(uploadFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am trying to invoke my R Rest API endpoint from my Java HTTP post.
#* #post /predict
mypredict <- function(data1) {
print(data1)
}
(1) Is my equivalent Java HTTP Post request correct?
(2) I am able to invoke the R rest endpoint using my curl command. But for some reason when i sent the POST request through my Java code, i see that data1 is not being passed as part of post request. I see this error in R.
<simpleError in print(data1): argument "data1" is missing, with no default>
I feel my Java equivalent curl implementation is wrong. Can someone help?
You specify content-type application/x-www-form-urlencoded (as curl does for this case) but supply an actual body (entity) that corresponds to multipart/form-data which is radically different. Instead use URLEncodedFormEntity containing (for your case) one NameValuePair something like this:
byte[] contents = Files.readAllBytes (new File(filepath).toPath());
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("data1", new String(contents,charset));
uploadFile.setEntity(new UrlEncodedFormEntity (list));
And you don't need addHeader("content-type",...) because setting the entity automatically supplies the content-type header (and content-length).
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.
I have a json string, I want to pass it to POST method. But the 'execute', and 'executeMethod ' are throwing error as below:
"The method execute(HttpUriRequest) in the type HttpClient is not applicable for the arguments (PostMethod)". i have included the depencencies.
my code:
StringRequestEntity requestEntity = new StringRequestEntity(
json-string,
"application/json",
"UTF-8");
PostMethod postMethod = new PostMethod("myUrl");
postMethod.setRequestEntity(requestEntity);
HttpResponse response = httpclient.execute(postMethod);
Is there any alternative way to do this? please help. thanks in advance
I use Apache HttpClient.
Snippet for calling a post method is as below.
String JSON_STRING="{"name":"Example"}";
StringEntity requestEntity = new StringEntity(
JSON_STRING,ContentType.APPLICATION_JSON);
HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);
HttpResponse rawResponse = httpclient.execute(postMethod);
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