I'm retrieving a PDF file from a web server java, returning a byte array.
Need save the PDF on the local machine using C #, but the file is saved completely in blank, I think it is because of the byte array format is different.
Here is my code:
StreamReader responseReader = new StreamReader(webStream);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/pdf";
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
responseReader.Close();
byte[] docByte = Encoding.ASCII.GetBytes(response);
File.WriteAllBytes(#"C:\file.pdf", docByte);
Any suggestions on how to save the PDF file normally?
Thank you for listening
// ...
Stream webStream = webResponse.GetResponseStream();
using (var stream = File.Create(#"C:\file.pdf"))
{
webStream.CopyTo(stream);
}
Why don't you do it simply with WebClient like this?
using System.Net;
using (WebClient webClient = new WebClient())
{
webClient.DownloadFile(URL, #"C:\file.pdf");
}
Related
All i am new to Jmeter and i am trying to create a rest api request that i can use to do some load test. I was able to authenticate and proceed to the next step of sending the post request.
Our Request is basically something like this
{"id" : 112, "someversion" : "2.0", "policyData" : "C:/TEMP/PGF/someinput.json" }
i was able to capture on the server what a sample request looks like. It seems that we are zipping and doing some base64 encoding before we send the request......
My main Question is how can i zip and encode this before posting so it can be similar to that format.
I have tried the following in jsr223 preprocessor:
import org.apache.commons.io.IOUtils;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64;
String bodyString = sampler.getArguments().getArgument(0).getValue();
byte [] requestBody = bodyString.getBytes();
ByteArrayOutputStream out = new ByteArrayOutputStream(requestBody.length);
GZIPOutputStream gzip = new GZIPOutputStream(out);
so in here i need to zip this. it seems it zipping and my request is as this:
I am thinking i just need to encode the policy data only and not the entire request ......
I need to do something like this in java and encrypt that file possibly before I send it in the request.
using (var cryptStream = new CryptoStream(streamWriter.BaseStream, new
ToBase64Transform(), CryptoStreamMode.Write, leaveOpen: true))
using (var gzipStream = new GZipStream(cryptStream,
CompressionMode.Compress))
using (var inputFile = new FileStream(requestData.policyData,
FileMode.Open, FileAccess.Read))
{
inputFile.CopyTo(gzipStream);
}
I think you need to:
Extract the path to file from the request body using JsonSlurper
GZip this file content
Encode the bytes array to Base64
Example code:
String bodyString = sampler.getArguments().getArgument(0).getValue();
File policyData = new File(new groovy.json.JsonSlurper().parseText(bodyString).policyData)
def fileStream = new ByteArrayOutputStream()
def gzipStream = new java.util.zip.GZIPOutputStream(fileStream)
gzipStream.write(policyData.bytes)
gzipStream.close()
def gzipped = fileStream.toByteArray()
fileStream.close()
log.info(gzipped.encodeBase64().toString())
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It
Thank you for your help... This is how i had initially solve my issue
String bodyString = sampler.getArguments().getArgument(0).getValue();
ByteArrayOutputStream rstBao = new ByteArrayOutputStream();
String JsonRequest = FileUtils.readFileToString(new
File("C:/TEMP/PGF/pgf_svc_input.json"));
GZIPOutputStream zos = new GZIPOutputStream(rstBao);
zos.write(JsonRequest.getBytes());
IOUtils.closeQuietly(zos);
byte[] bytes = rstBao.toByteArray();
//Here is where i am able to encode the bytes to base 64
Base64.encodeBase64String(bytes);
vars.put("postDataEncoded64",Base64.encodeBase64String(bytes));
log.info("khemlall this is the content"+ Base64.encodeBase64String(bytes));
log.info(vars.get("postDataEncoded64"));
rstBao.close()
In the body of my request i added the variable:
{
"id":"22351",
"pmmVersion":"2.0",
"policyData" : "${postDataEncoded64}"
}
I am trying to attach a png file. Currently when I sent the email, the attachment is 2x bigger than the file should be and an invalid png file. Here is the code I currently have:
import com.sendgrid.*;
Attachments attachments = new Attachments();
String filePath = "/Users/david/Desktop/screenshot5.png";
String data = "";
try {
data = new String(Files.readAllBytes(Paths.get(filePath)));
} catch (IOException e) {
}
byte[] encoded = Base64.encodeBase64(data.getBytes());
String encodedString = new String(encoded);
attachments.setContent(encodedString);
Perhaps I am encoding the data incorrectly? What would be the correct way to 'get' the data to attach it?
With respect, this is why Python presents a problem to modern developers. It abstracts away important concepts that you can't fully understand in interpreted languages.
First, and this is a relatively basic concept, but you can't convert arbitrary byte sequences to a string and hope it works out. The following line is your first problem:
data = new String(Files.readAllBytes(Paths.get(filePath)));
EDIT: It looks like the library you are using expects the file to be base64 encoded. I have no idea why. Try changing your code to this:
Attachments attachments = new Attachments();
String filePath = "/Users/david/Desktop/screenshot5.png";
try {
byte[] encoded = Base64.encodeBase64(Files.readAllBytes(Paths.get(filePath)));
String encodedString = new String(encoded);
attachments.setContent(encodedString);
} catch (IOException e) {
}
The only issue you were having is that you were trying to represent arbitrary bytes as a string.
Take a look at the Builder class in the repository here. Example:
FileInputStream fileContent = new FileInputStream(filePath);
Attachments.Builder builder = new Attachments.Builder(fileName, fileContent);
mail.addAttachments(builder.build());
How to write java code for egnyte chunked upload and send to rest service of egnyte api.
https://developers.egnyte.com/docs/read/File_System_Management_API_Documentation#Chunked-Upload
long size = f.getTotalSpace();
int sizeOfFiles = 1024 * 1024;// 1MB
byte[] buffer = new byte[sizeOfFiles];
ResponseEntity<String> responseEntity = null;
String fileName = f.getName();
String url = DOWNLOAD_OR_UPLOAD + "-chunked" + egnyteSourcePath + f.getName();
HttpHeaders headers = buildEgnyteEntity();
HttpEntity entity = new HttpEntity<>(headers);
//try-with-resources to ensure closing stream
try (FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis)) {
int bytesAmount = 0;
while ((bytesAmount = bis.read(buffer)) > 0) {
//write each chunk of data into separate file with different number in name
String filePartName = String.format("%s.%03d", fileName, partCounter++);
File newFile = new File(f.getParent(), filePartName);
responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
}
}
return responseEntity;
I think there's a couple of things missing in your code.
First thing is that you don't specify required headers. You should provide X-Egnyte-Chunk-Num with int value with number of your chunk, starting from 1. In X-Egnyte-Chunk-Sha512-Checksum header you should provide SHA512 checksum.
Second thing is that first request will give you an UploadId in response header in X-Egnyte-Upload-Id. You need to specify that as a header in your second and following requests.
Third thing is that I don't see you use your bytesAmount in the request. I'm not sure you're providing the data.
I'm not a Java guy, more of a C# one, but I've written a post how to upload and download big files with Egnyte API on my blog: http://www.michalbialecki.com/2018/02/11/sending-receiving-big-files-using-egnyte-api-nuget-package/. This can give you an idea how sending loop can be structured.
Hope that helps.
I am using Apache POI and I am trying to send a xlsx file as HTTP request and get it back as response. I am using jayway restassured for making HTTP requests.
Here is the part of the code where I send the request
File file = new File("path");
String response = given().multipart(file).when().post("URL").getBody().asString();
byte[] bytes = response.getBytes("ISO-8859-1");
InputStream stream = new ByteArrayOutputStream(bytes);
try
{
XSSFWorkbook workbook = new XSSFWorkbook(stream);
}
catch(Exception e){
e.printStackTrace();
}
Here is the code where the response is generated for the request
XSSFWorkbook workBook; //this workBook has the workbook sent as HTTP request
//code to make changes in workBook
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
workBook.write(outStream);
byte[] byteArray = outStream.toByteArray();
String responseBody = new String(byteArray, "ISO-8859-1");
context.response().putHeader("Content-Type", "multipart/form-data").setStatusCode(200).end(responseBody);
So, what I am trying to do is send a xlsx file as request make some changes and get it back as a string response, convert it back to xssfworkbook. When converting back I get error in the following line-
XSSFWorkbook workbook = new XSSFWorkbook(stream);
The error I get is
java.util.zip.ZipException: invalid code lengths set
You cannot simply send the byte-array as ISO-8859-1 encoded text the way you attempt.
There will be special characters that might get replaced/truncated/modified.
Currently you mix binary data and a text-only channel (HTTP). You will need to do it differently, either use a binary data transfer and not convert it to String or use some binary-to-text representation, see e.g. https://en.wikipedia.org/wiki/Binary-to-text_encoding, the most common one being Base64
Use
InputStream stream = new ByteArrayInputStream(bytes);
I'm using post and get request from Qualtrics api. They have sample code in java but I have a hard time to convert it into .net environment. The difficulity part is the download exported file(zip file). My question is how to implement the httpClient.execute in C#? I think in java it could hold the object without download into your physical drive and unzip the file....
Their sample code in java:
HttpGet statusGet = new HttpGet(fileUrl);
statusGet.setHeader("X-API-TOKEN", API_TOKEN);
HttpResponse response = httpClient.execute(statusGet);
// Extract exported file
ZipInputStream zs = new ZipInputStream(response.getEntity().getContent());
ZipEntry entry;
while ((entry = zs.getNextEntry()) != null)
{
FileOutputStream out = new FileOutputStream("./" + entry.getName());
IOUtils.copy(zs, out);
out.close();
}
}
Here's mine in c#:
using (var clientgetfile = new HttpClient())
{
clientgetfile.DefaultRequestHeaders.Accept.Clear();
clientgetfile.DefaultRequestHeaders.Add("X-API-TOKEN", "mytoken");
clientgetfile.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/zip"));
var response = clientgetfile.GetAsync(fileUrl);
DownloadFile = response.Result;
var byteArray = DownloadFile.Content.ReadAsStreamAsync().Result;
....