How to send an image to a Testrun in Testrail using Multipart POST call in JAVA?

121 views Asked by At

I'm trying to attach the screenshot taken after the failure of the test. Screenshots are getting captured and stored in a folder. I'm trying to send the screenshot from that folder to Testrail using Multipart Post call and I'm getting 400 response.

Code that I tried for sending an image through post call, I'm getting 400 response with this post call.

Does anyone know the reason behind getting 400 response, Is there anything that has to be modified at the code level? Is there other alternative way to send an image to a Testrun in Testrail through post call?

HttpClient httpclient = new DefaultHttpClient();

httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

String rawURL = ".../index.php?/api/v2/add_attachment_to_result/{result_id}";
URL url = new URL(rawURL);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestProperty("Authorization",
  "Basic " + Base64.getEncoder().encodeToString(
            (userName + ":" + userPassword).getBytes()
          )
        );

HttpPost httppost = new HttpPost(".../index.php?/api/v2/add_attachment_to_result/{result_id}");
File file = new File("file path");

MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);


httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();

System.out.println(response.getStatusLine());
if (resEntity != null) {
  System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
  resEntity.consumeContent();
}

httpclient.getConnectionManager().shutdown();

I'm getting 400 response with this post call.

1

There are 1 answers

0
Sergi On

Try using builder for multipart entity:

            final MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create().addBinaryBody("attachment", file);
            post.setEntity(multipartBuilder.build());