I got the attached img value as response from the SharePoint server but can not write it on the docx file. The file download API using Postman is giving same response and if I save Postman response to docx file then it is saving perfectly but not from Java side. If I write same response to a docx file using Java, the file is corrupted.
I am using this REST API to download the file from Sharepoint:
SiteURL/_api/web/getfilebyserverrelativeurl('relativeURL/Shared Documents/test.docx')/$value
Most likely server is returning the document (docx) as binary (application/octet-stream). Your code saves the document's string representation:
ResponseEntity<String> response = restTemplate.exchange(fileUrl, HttpMethod.GET, request, String.class);
String responseStrFromSharePoint = response.getBody();
That's why the file could not be decoded by application. Instead save the exact binary (bytes) returned by the server as the following snippet shows:
ResponseEntity<byte[]> response = restTemplate.exchange(fileUrl, HttpMethod.GET, request, byte[].class);
byte[] responseStrFromSharePoint = response.getBody();
Other parts of the code seems fine.
Related
In Spring Boot the zip file that comes as a response has a corrupted structure before saving, but there is no problem when I save it physically. I need to take the file in the zip file and process the information in the database, but I cannot physically download this file because I am using GCP. How can I extract the file in this zip file that comes as a response?. How can I solve this please help.
Here is what it looks like in response.body() before saving (part of it):
"PK C`iUq �=n 緰) bu_customerfile_22110703_B001_10292121141�]i��������RI%U�v��CJ� ���×��My��y/ίϹ�������=>����}����8���}~}~yz�������ͲL��
�o�0�fV�29f�����6$K�c$�F��/�8˳�L��_�QaZ-q�F�d4γE�[���(f�8�D�0��2_��P"�I�A��D��4�߂�����D��(�T�$.��<�,���i]Fe�iM�q<ʨ�Olmi�(&���?�y�y4��<��Q�X�ޘp�#�6f-.F����8����"I㢨ҤU]�E��WI� %#������(W�8*0c�p:L��:� �}�G����e<����a�"
Here is the request call:
OkHttpClient client1 = new OkHttpClient().newBuilder()
.build();
MediaType mediaType1 = MediaType.parse("text/plain");
RequestBody body1 = RequestBody.create(mediaType1, "");
Request request1 = new Request.Builder()
.url(vers)
.method("POST", body1)
.addHeader("Cookie", "ASP.NET_SessionId=44dxexdxass5mtf00udjfwns")
.build();
Response response1 = client1.newCall(request1).execute();
String data = response1.body().string();
Would it be a matter of encoding type? String is of type UTF-16 (I think). Try a different datatype that is more like an array/vector of bytes.
Try something like what is mentioned here:
Having trouble reading http response into input stream
Update: Get the response as a stream of bytes and feed it into a ZipInputStream object as shown here https://zetcode.com/java/zipinputstream/#:~:text=ZipInputStream%20is%20a%20Java%20class,both%20compressed%20and%20uncompressed%20entries.
Then iterate over the contained files to find the one you need. Then retrieve the stream associated with the zipped file. Then you can read from there. (I realize that is a bit of handwaving, but it's been a while since I used Zip files and Java.) That should get you down the correct path.
I am trying to upload a file from client to server the client uploads the file to the server using the curl command
client command:
curl -X POST -T pom.xml http://localhost:8070/put --header "origmd5":"7AB4E6F0A4A2D3CBB200DB1677D99AD75"
Now in the controller i.e at the server side the code is as follows
server side:
#PostMapping(value="readFile")
public ResponseEntity<?> uploadfile(#RequestBody String filecontent) throws IllegalStateException, IOException {
System.out.println(filecontent);//prints the content which is inside the file uploaded by client
return null;
}
1.Now the problem statement is how do we get the file name that has been sent by the client the contents of the file can be parsed in the request body but how to get the file name?
#RequestBody String filecontent
2.i am using string like above to parse request body (i.e content of file is stored in String) is this the correct way storing contents of file in string?
You actually need MultipartFile which will give you all the information related to the uploaded file.
uploadfile(#RequestParam("file") MultipartFile file){
String fileName = file.getOriginalFilename()
}
Using Multipart might be a better solution when uploading files:
#PostMapping(value="readFile")
public ResponseEntity<?> uploadfile(#RequestParam(value="file") MultipartFile fileContent){
}
I am trying to download a file from a REST service using JAX-RS.
This is my code which invokes the download by sending a GET request:
private Response invokeDownload(String authToken, String url) {
// Creates the HTTP client object and makes the HTTP request to the specified URL
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
// Sets the header and makes a GET request
return target.request().header("X-Tableau-Auth", authToken).get();
}
However I am facing problems converting the Response into an actual File object. So what I did is the following:
public File downloadWorkbook(String authToken, String siteId, String workbookId, String savePath)
throws IOException {
String url = Operation.DOWNLOAD_WORKBOOK.getUrl(siteId, workbookId);
Response response = invokeDownload(authToken, url);
String output = response.readEntity(String.class);
String filename;
// some code to retrieve the filename from the headers
Path path = Files.write(Paths.get(savePath + "/" + filename), output.getBytes());
File file = path.toFile();
return file;
}
The file which is created is not valid, I debugged the code and noticed that output contains a String like that (much larger):
PK ͢�F���� �[ Superstore.twb�ysI�7����ߡ���d�m3��f���
Looks like binary. Obviously there is something wrong with the code.
How do I get the HTTP response body as a string from the Response object?
Edit:
Quote from the REST API reference about the HTTP response:
Response Body
One of the following, depending on the format of the workbook:
The workbook's content in .twb format (Content-Type: application/xml)
The workbook's content in .twbx format (Content-Type: application/octet-stream)
As you noticed yourself, you're dealing with binary data here. So you shouldn't create a String from your response. Better get the input stream and pipe it to your file.
Response response = invokeDownload(authToken, url);
InputStream in = response.readEntity(InputStream.class);
Path path = Paths.get(savePath, filename);
Files.copy(in, path);
1) I assume by this point you're clear on the difference between "binary file" and "text file". And that you can only capture the latter into a "string".
2) Sebastian gave you excellent advice for capturing a binary file (+1, Sebastian!). VERY IMPORTANT: you should always set the MIME type (Content-Type: xxx/yyy)in cases like this. Here is another link that might be useful.
3) Finally, there are cases where you might WANT to treat "binary" data as text. This is how e-mail attachments work with SMTP (a text protocol). In these cases, you want to use Base64 Encoding. For example: JAX-RS | Download PDF from Base64 encoded data
I am trying to download a PDF file from a response of Java REST call after custom authentication check.
I can see downloaded file but it is empty file.
Below is my code snippet.
//Custom HTTPClient
HTTPAuthClient client = new HTTPAuthClient(url,username,password)
Request request = new Request(downloadURL); //I'm downloading file content of an URL.
Response response = client.executeGet(request);
String response1 = response.getResponseBody();
InputStream is = new ByteArrayInputStream(response.getBytes());
response.setContentType("Content-type",application/pdf); //here response is //javax.servlet.HttpServletResponse
response.setHeader("Content-Disposition","attachment;filename="myfile.pdf");
IOUtils.copy(is,response.getOutPutStream());
response.flushBuffer();
With this code I could download the file but when I open the file and verified there is no data.
As part of response body also I can see some data.
Could you please help me out where I'm doing mistake I tried many options but did not find solution.
How can you use setContentType like this
response.setContentType("Content-type",application/pdf);
If only one avalible param in this method is String void setContentType(String type) so your method should be:
response.setContentType("application/pdf");
Java Doc to be sure.
I am attempting to replicate, using java and Jersey, uploading a file to ZenDesk, to be used as an attachment on a ticket. The example code from ZenDesk uses curl with a --data-binary parameter, referencing a file on disk.
I am using an SDK client that I found on git as my starting point, everything about this SDK works with the exception of file uploads.
Here is the code that I currently have doing the upload:
File fileToUpload = new File(attachment.getUrl());
FileDataBodyPart filePart = new FileDataBodyPart(attachment.getFilename(), fileToUpload, MediaType.APPLICATION_OCTET_STREAM_TYPE);
FormDataContentDisposition.FormDataContentDispositionBuilder builder = FormDataContentDisposition.name(filePart.getName());
builder.fileName(fileToUpload.getName());
builder.size(fileToUpload.length());
filePart.setFormDataContentDisposition(builder.build());
FormDataMultiPart multiPart = new FormDataMultiPart();
multiPart.bodyPart(filePart);
multiPart.field("filename", attachment.getFilename());
ClientResponse cr = rootResource.path("/api/v2/uploads.json")
.accept(MediaType.APPLICATION_JSON_TYPE)
.type(MediaType.MULTIPART_FORM_DATA_TYPE)
// .post(AttachmentWrapper.class, attachment);
.post(ClientResponse.class, multiPart);
This results in an internal server error 500 response from ZenDesk.
I have tried several different arrangements of the parameters, with no success.
The project that I'm using as a starting point is located here: Zendesk-API-Client
The problem with the original project is that the file being uploaded doesn't have its content available on the ZenDesk server, it is just the JSON defining the file.
Thanks,
Allen