Please find below jersey client code to upload multipart file:
String url = "http://localhost:7070"
Client client = Client.create();
WebResource webresource = client.resource(url);
File file = new File("C://Data//image1.jpg");
File thumbnail = new File("C://Data/image2.jpg");
InputStream isthumbnail = new FileInputStream(thumbnail);
InputStream isfile = new FileInputStream(file);
FormDataMultiPart multiPart = new FormDataMultiPart();
FormDataBodyPart bodyPart1 = new FormDataBodyPart(FormDataContentDisposition.name("Thumbnail").fileName("thumbnail").build(), isthumbnail, MediaType.APPLICATION_OCTET_STREAM_TYPE);
FormDataBodyPart bodyPart2 = new FormDataBodyPart(FormDataContentDisposition.name("File").fileName("file").build(), isfile, MediaType.APPLICATION_OCTET_STREAM_TYPE);
multiPart.bodyPart(bodyPart);
multiPart.bodyPart(bodyPart1);
//New Headers
String fileContentLength = "form-data; contentLength=\""+Long.toString(file.length())+ "\"";
String thumbnailContentLength = "form-data; contentLength=\""+Long.toString(file.length())+ "\"";
final ClientResponse clientResp = webresource.type(MediaType.MULTIPART_FORM_DATA_TYPE).accept(MediaType.APPLICATION_XML).post(ClientResponse.class, multiPart);
System.out.println("File Upload Success with Response"+clientResp.getStatus());
I need to add the String fileContentLength and thumbnailContentLength as header
Content-Length.
How do i add the headers as part of multipart and post the request?Any help would be appreciated
Use a FormDataContentDisposition as an argument to FormDataBodyPart(FormDataContentDisposition formDataContentDisposition, Object entity, MediaType mediaType).
final FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
final String value = "Hello World";
final FormDataContentDisposition dispo = FormDataContentDisposition
.name("file")
.fileName("test.txt")
.size(value.getBytes().length)
.build();
final FormDataBodyPart bodyPart = new FormDataBodyPart(dispo, value);
formDataMultiPart.bodyPart(bodyPart);
Related
Can anyone tell me what I am missing here, same code is working when response size is less. Here in the response getting xls file in encrpypted format. When file size is big, getting connection reset error.
Code to make a webservice HTTP request
String responseString = "";
String outputString = "";
String wsURL = System.getenv("ORACLE_ENDPOINT");
URL url = new URL(wsURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
String xmlInput = requestPayloader(requestId_1, GroupId, RequestId_2, interfaceType);
byte[] buffer = new byte[xmlInput.length()];
buffer = xmlInput.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();
String SOAPAction = "url";
// Set the appropriate HTTP parameters.
// refer username and password from Key Valut
KeyVault keyVault = new KeyVault();
String userName = keyVault.GetSecretFromVault(System.getenv("ORACLE_ENDPOINT_USERNAME"));
String password = keyVault.GetSecretFromVault(System.getenv("ORACLE_ENDPOINT_PASSWORD"));
// String auth = System.getenv("ORACLE_ENDPOINT_USERNAME") + ":" +
// System.getenv("ORACLE_ENDPOINT_PASSWORD");
String auth = userName + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.UTF_8));
String authHeaderValue = "Basic " + new String(encodedAuth);
httpConn.setRequestProperty("Content-Type", "application/soap+xml");
httpConn.setRequestProperty("SOAPAction", SOAPAction);
httpConn.setRequestProperty("Authorization", authHeaderValue);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setReadTimeout(0);
OutputStream out = httpConn.getOutputStream();
out.write(b);
//out.close();
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
return outputString;
I am trying to upload a file to cloud using jersey client. But here I am getting below response.
InboundJaxrsResponse{context=ClientResponse{method=POST, uri=http://test.net/hello, status=400, reason=400}}
and the source is as below.
final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();
final JsonObjectBuilder formJson = Json.createObjectBuilder();
formJson.add("name", fileName);
formJson.add("parent", 0);
String jsonStr = formJson.build().toString();
final FileDataBodyPart filePart = new FileDataBodyPart("file", new File(fileLocation));
FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
final FormDataMultiPart multiPart = (FormDataMultiPart) formDataMultiPart
.field(jsonStr, MediaType.MULTIPART_FORM_DATA).bodyPart(filePart);
multiPart.setContentDisposition(FormDataContentDisposition.name("file").fileName(fileLocation).build());
final WebTarget target = client.target("http://test.net/hello");
final Response response = target.request().header("Content-Type", "multipart/form-data")
.header("instanceid", "b05642c8-d231-48fe-a163-d978a6208d98")
.post(Entity.entity(multiPart, "multipart/form-data"));
Can any one help me to out this issue.
Thanks,
The body is in raw text format and the request is a POST method. I am using this code.
#RequestMapping(value = "/run", method = RequestMethod.POST)
ResponseEntity<String> runReport(){
RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl = "requestURL";
String auth = "username:password";
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(Charset.forName("US-ASCII")) );
String authHeader = "Basic " + new String( encodedAuth );
// Defining the Headers
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("Authorization", authHeader);
headers.add("Content-Type", "multipart/form-data; boundary=\"Boundary_1_1153447573_1465550731355\"");
headers.add("Accept", "multipart/form-data");
// Defining the Body
String outputFormatType = "pdf";
String body = "--Boundary_1_1153447573_1465550731355\n"
+"Content-Type: application/json\n"
+"Content-Disposition: form-data;" + " "+"name=\"ReportRequest\"\n\n"
+"{\"byPassCache\":true,\"flattenXML\":false,\"attributeFormat\":"+ "\""+outputFormatType+"\"" +"}\n"
+"--Boundary_1_1153447573_1465550731355--";
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("username", "password"));
ResponseEntity<String> result = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, entity, String.class);
return result;
}
It was solved by removing the following line:
restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("username", "password"));
As it was already being added in header. And added the body as a parameter to the HttpEntity constructor:
HttpEntity<String> entity = new HttpEntity<>(body, headers);
String reqURL = baseUrl + data_oauth.get(PropLoad.getTestXmlData("URL"));
Template template = new Template();
String updatedUrl = template.getUpdatedURL(reqURL);
Map<String, String> headers = Template.getRequestData(data_oauth,PropLoad.getTestXmlData("HEADER"));
headers.entrySet().toString();
String updatedAuthor = template.getAuthorizationHeader(headers, methodDesc);
headers.put("Authorization", updatedAuthor);
String xmlRequest = Template.generateStringFromResource(data_oauth,"xmlbody");
Response response = webCredentials_rest.postCallWithHeaderAndBodyParamForXml(headers, xmlRequest, updatedUrl);
// am getting Unmarshalled as in response, can any help me on posting an POST request with XML body in it
You can send it like this:
URL url = new URL(urlString);
URLConnection connenction = url.openConnection();
OutputStream output = connenction.getOutputStream();
InputStream input = new FileInputStream(xmlFile);
byte[] buffer = new byte[4096];
int len;
while ((len = input .read(buffer)) >= 0) {
out.write(buffer, 0, len);
}
input .close();
output.close();
And read the response like this:
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connenction.getInputStream()));
String readLine = reader.readLine();
while (readLine != null) {
stringBuilder.append(readLine);
readLine = br.readLine();
}
i was trying to send a mail from cq-DAM but failed.
i can send files from my own pc, i want to get the files from DAM
here is the code ::
#SuppressWarnings("unchecked")
final Enumeration<String> parameterNames = request.getParameterNames();
final Map<String, String> parameters = new HashMap<String, String>();
while (parameterNames.hasMoreElements()) {
final String key = parameterNames.nextElement();
parameters.put(key, request.getParameter(key));
}
Resource templateRsrc = request.getResourceResolver().getResource("/etc/notification/send-email.html");
String mailId = request.getParameter("mailId");
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("/media/intelligrape/MyFiles/Xtra/Crafting/Paper Work/images.jpg");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Picture of John");
attachment.setName("John");
int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
try {
final MailTemplate mailTemplate = MailTemplate.create(templateRsrc.getPath(), templateRsrc.getResourceResolver().adaptTo(Session.class));
final HtmlEmail email = mailTemplate.getEmail(StrLookup.mapLookup(parameters), HtmlEmail.class);
logger.error("PROPERTIES**************************** "+parameters);
email.addTo(mailId);
email.attach(attachment);
URL url = new URL("<any URL except localhost>");
String cid = email.embed(url, "Apache logo");
email.setHtmlMsg("<html><body>The ig logo - <img src=\"cid:"+cid+"\"></body></html>");
email.setTextMsg("Your email client does not support HTML messages");
messageGateway = messageGatewayService.getGateway(HtmlEmail.class);
messageGateway.send(email);
thanks in advance..:)
You can get InputStream of the DAM image and convert it to ByteArrayDataSource and then use attach(datasource,name,description) method to attach the DAM image to email.
Node contentNode = imageNode.getNode("jcr:content");
Binary imageBinary = contentNode.getProperty("jcr:data").getBinary();
InputStream imageStream = imageBinary.getStream();
ByteArrayDataSource imageDS = new ByteArrayDataSource(imageStream,"image/jpeg");
email.attach(imageDS,"Some Image","Some Description");