POST Request with multipart/form-data Java code - java

I'm using Activiti and Eclipse. Now I want to upload my process to web UI through restful API.
Follow the document, I test it successfully in Postman.
My request has a basic auth:
enter image description here
And this is body with a file to upload:
enter image description here
My problem is I don't know how to do that request in Java code, I write some code following some Stack's post but it doesn't work.
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost("http://localhost:8080/activiti-rest/service/repository/deployments");
request.addHeader("content-type","multipart/form-data");
//convert credentials to base64
byte[] credentials = Base64.encodeBase64(("kermit:kermit").getBytes(StandardCharsets.UTF_8));
request.setHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8));
request.setEntity(new FileEntity(new File("C:/Users/ISC-HaoNMN/Desktop/ActivitiProcess.bar")));
httpClient.execute(request);
Can someone give me a sample code. Thank you!

Related

Firebase Dynamic Link Rest API - 400 Bad Request

I am transitioning an existing service from using google url shortener api to try and use Firebase Dynamic Links. I have linked a project from the Google Cloud Platform, and setup a "dummy" android app so that I can have the app domain for the dynamic links. I am trying to use the REST API to shorten urls for very long urls that can't be handled by a third party. I have tried sending using:
ObjectMapper mapper = new ObjectMapper();
HttpPost httpPost = new HttpPost("https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=****");
FirebaseDynamicLinkInfo dynamicLinkRequest = new FirebaseDynamicLinkInfo();
dynamicLinkRequest.setDynamicLinkDomain("zw5yb.app.goo.gl");
dynamicLinkRequest.setLink(assetUrl);
httpPost.setEntity(new StringEntity(mapper.writeValueAsString(dynamicLinkRequest)));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
responseBody = httpClient.execute(httpPost, responseHandler);
I am getting a 400 Bad Request when I post the request to the API (on the httpCLient.execute line. I have double checked my api-key. I have also tried using just the longDynamicLink parameter, and it gets the 400 Bad Request Response.
Any ideas of where I could be going wrong?
Thanks,
Ben
I contacted Google Support on this one, and I wasn't UrlEncoding my querystring parameters on the deep link. After encoding the link, the request was successful. I went back to using passing json that just had a longDynamicLink property (as opposed to the dynamicLinkInfo object in my original post). Here is what it looks like:
String myEscapedUrl = "https://zw5yb.app.goo.gl/?link=" + URLEncoder.encode(assetUrl, "UTF-8");
FirebaseDynamicLinkRequest dynamicLinkRequest = new FirebaseDynamicLinkRequest(myEscapedUrl);
httpPost.setEntity(new StringEntity(mapper.writeValueAsString(dynamicLinkRequest)));
// inform the server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
responseBody = httpClient.execute(httpPost, responseHandler);

Sending a key and file using MultipartEntityBuilder

I don't have much experience with networking and my Googling skills don't seem to get me any further than this.
I need to send a file to a server with "file" being the HTTP POST key. Here is what I have:
MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
mpEntity.addBinaryBody("file", image);//set up the object to send
HttpPut put = new HttpPut("http://address:port");
put.setEntity(mpEntity.build());//put the object to be sent
//try sending
try {
HttpResponse response = client.execute(put);
...
I'm getting a 404 error when I process the response using an InputStream. The server is up and running and works fine when I test it from the terminal.
Add the content type and the name of the file to the binary body like this:
mpEntity.addBinaryBody("file", image, ContentType.create("image/jpeg"), "image_name.jpg");

POST request to server using java URLConnnection with params and file inputs

POST request to server using java URLConnnection
I need to send a POST request with the two parameters below:
param1=value1
param2=value2
And also I need to send a file.
In the case of Apache these 2 two(sending params and file) things are handled like below
post.setQueryString(queryString) // queryString is url encoded for eg: param1=value1&param2=value2
post.setRequestEntity(entity) // entity is constructed using file input stream with corresponding format
Please let me know if you have anything related to this problem.
Please note: When I try using Google Chrome REST client plug-in, I am getting the response as below (tried with all request content-types)
UNSUPPORTED FILE FORMAT: 'multipart/form-data' is not a supported content-type
Response code is 400.
Try this API from Apache to send request internally with POST method.
The below is the sample Code to use API
List<org.apache.http.NameValuePair> list =new ArrayList<org.apache.http.NameValuePair>();
HttpPost postMethod = new HttpPost("http://yoururl/ProjectName");
list.add(new BasicNameValuePair("param1", "param1 Value")) ;
postMethod.setEntity(new UrlEncodedFormEntity(list));
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(postMethod);
InputStream is = response.getEntity().getContent();

Read file of content-disposition with java

I am developing a web-app that needs to query an ontology through a REST-API.
If I call the API through the browser, it opens a pop-up "Save As" through which I can save the file.
This is because the header of the response contains:
Content-Disposition: attachment; filename = query-result.srx
The problem is that I would like to receive the file within my web-app without using the browser.
The web-app is write on java and I use Apache HttpClient for send and receive, HTTP request and response:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
If I try to get the entity's content:
httpResponse.getEntity().getContent()
It return a useless value.
It 's something that you can do with this library, or should I use another library.
I found another question similar to mine but no one answered.
java-javascript-read-content-disposition-file-content
Thanks to all who answer me!
I realized that the error was in the query that I used the REST API. So the operations I did in Java were correct. With the command
httpResponse.getEntity().getContent()
you can take the content that is returned even if this file is described in the content-disposition.
Thanks to #Julian Reschke

Downloading a file using a REST POST call in java

I have a REST service which returns a file when it is called via a POST call with an XML file as the parameter. My goal is to access the service using a client (a simple httppost call in a java class). So far, I am doing as below:
DefaultHttpClient defaultHtppclient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("resturl");
StringEntity input = new StringEntity("input xml file ");
input.setContentType("application/xml");
postRequest.setEntity(input);
HttpResponse response = defaultHtppclient.execute(postRequest);
I am getting the contents of the file when I convert the response using :
String content = EntityUtils.toString(response.getEntity());
But I am struggling to download the file as such from the java class. When I trigger the URL in Firefox HTTP resource test. I am getting the headers as:
Content-Disposition: attachment; filename = filenameFromserver
Content-Type: application/octet-stream
Is there any way to download the file as such from the client ?
The call you're making is expecting application/xml, the server is sending you an octet-stream.
You'll have to read in the bytes it's sending you and write them out to the file that you want. I'd recommend searching around on how to read in an octet stream.
For an example take a look at this post:
Reading binary file from URLConnection

Categories

Resources