Kong / unirest-java

Unirest in Java: Simplified, lightweight HTTP client library.
http://kong.github.io/unirest-java/
MIT License
2.6k stars 594 forks source link

Unable to upload a file using Unirest #433

Closed amuthansakthivel closed 2 years ago

amuthansakthivel commented 2 years ago

Describe the bug Unable to use form data in body to upload file. I am trying to use Unirest to add attachment to the test rail (test management tool). Curl code looks like this and if someone could help me with the corresponding unirest code, it will be helpful.

$ curl -H "Content-Type: multipart/form-data" \ -u "user@example.com:" \ -F "attachment=@C:\image.jpg" \ "https://example.testrail.io/index.php?/api/v2/add_attachment_to_result/1

In postman, it looks something like this.

Screenshot 2022-03-04 at 11 26 23 AM

I tried below ways in unirest and nothing worked.

Unirest.config()
                .setDefaultBasicAuth("username","password")
                .defaultBaseUrl("url")
                .interceptor(new UniRestListener());
Way 1 :
        File file = new File(System.getProperty("user.dir") + "/index.html");

        RequestBodyEntity request = Unirest.post("/add_attachment_to_run/201")
                .header("Content-Type","multipart/form-data")
                .body(new FileInputStream(file).readAllBytes());

Way 2 : 

Unirest.post("/add_attachment_to_run/"+testRunID)
                .multiPartContent()
                .contentType(ContentType.MULTIPART_FORM_DATA.toString())
                .field("file",new File(System.getProperty("user.dir")+"/index.xml"),"attachment");

Way 3:

Unirest.post("/add_attachment_to_run/"+testRunID)
.header("Content-Type", "multipart/form-data")
                .field("file",new File(System.getProperty("user.dir")+"/index.xml"));

All I could get was 400 bad request (POST request not formatted properly or invalid result ID)

Expected behavior I should be able to to add attachment to test rail via unirest

Screenshots If applicable, add screenshots to help explain your problem.

Environmental Data:

Additional context https://www.gurock.com/testrail/docs/api/getting-started/accessing/#ExampleAttachmentUpload

ryber commented 2 years ago

stop setting the content type yourself, Unirest handles that and does the proper boundary part which you are missing.