How to send Request file path in JSON request in Jmeter Test - java

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}"
}

Related

How to properly open a png file

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 convert Scala FilePart as File (Java) to use in multipart-form data?

I have a method that already have an FilePart[TemporaryFile] and i will call another method to send a multi-part form data. This method is using scala play 2.4.X and i have to send it using ning method below:
def sendFile(file: FilePart[TemporaryFile]): Option[Future[Unit]] = {
val asyncHttpClient:AsyncHttpClient = WS.client.underlying
val postBuilder = asyncHttpClient.preparePost(s"${config.ocrProvider.host}")
val multiPartPost = postBuilder
.addBodyPart(new StringPart("access_token",s"${config.ocrProvider.accessToken}"))
.addBodyPart(new StringPart("typename",s"${config.ocrProvider.typeName}"))
.addBodyPart(new StringPart("action",s"${config.ocrProvider.actionUpload}"))
.addBodyPart(new FilePart(**expects java.io.File not FilePart**)
}
How can i take advantage of this parameter and send as java.io.File?
You need to write the content of file: FilePart[TemporaryFile] to disk and then use that file for constructing the new multipart request. You can see this example Scala File Upload
val tempFile = new File("/tmp/some/path")
file.ref.moveTo(tempFile)
val filePart = new FilePart(tempFile)

Convert byteArray to XSSFWorkbook using Apache POI

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);

Trouble to save PDF file from a java web service using C#

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");
}

How can I See the content of a MultipartForm request?

I am using Apache HTTPClient 4. I am doing very normal multipart stuff like this:
val entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("filename", new FileBody(new File(fileName), "application/zip").asInstanceOf[ContentBody])
entity.addPart("shared", new StringBody(sharedValue, "text/plain", Charset.forName("UTF-8")));
val post = new HttpPost(uploadUrl);
post.setEntity(entity);
I want to see the contents of the entity (or post, whatever) before I send it. However, that specific method is not implemented:
entity.getContent() // not defined for MultipartEntity
How can I see what I am posting?
Use the org.apache.http.entity.mime.MultipartEntity writeTo(java.io.OutputStream) method to write the content to an java.io.OutputStream, and then convert that stream to a String or byte[]:
// import java.io.ByteArrayOutputStream;
// import org.apache.http.entity.mime.MultipartEntity;
// ...
// MultipartEntity entity = ...;
// ...
ByteArrayOutputStream out = new ByteArrayOutputStream(entity.getContentLength());
// write content to stream
entity.writeTo(out);
// either convert stream to string
String string = out.toString();
// or convert stream to bytes
byte[] bytes = out.toByteArray();
Note: this only works for multipart entities small enough to be read into memory, and smaller than 2Gb which is the maximum size of a byte array in Java.
Following would help for sure:
ByteArrayOutputStream content = new ByteArrayOutputStream();
httpEntity.writeTo(content);
logger.info("Calling "+url+" with data: "+content.toString());
The above has a fix in comparison to the first answer, there is no need to pass any parameter to ByteArrayOutputStream constructor.
Do you not know the content? Although, you are building the StringBody by supplying sharedValue. So, how could it be different than sharedValue.
I have printed the Multipart request by following code, You can try like
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
entity.writeTo(bytes);
String content = bytes.toString();
Log.e("MultiPartEntityRequest:",content);

Categories