Kong / unirest-java

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

UnirestInstance.request() Method behaves differently than expected. #490

Closed BBackJK closed 9 months ago

BBackJK commented 10 months ago

Describe the bug

I am trying to commonly call the http method through UnirestInstance, but the header and query parameters work normally, but the field() method used when x-www-urlencoded and the body() method used when application/json do not work.

To Reproduce

@GetMapping("/api/v1/direct/call/unirest")
    ResponseEntity<String> unirest() {

        HttpRequestWithBody request = Unirest.request("POST", "http://localhost:8080/api/v1/post1");
        request.header("Content-Type", "application/json");
        request.body(SampleRequestDto.of("postJson1", "postJson2", "postJson3"));

        HttpResponse<String> response1 = request.asString();

        HttpResponse<String> response2 = Unirest.request("POST", "http://localhost:8080/api/v1/post1")
                .header("Content-Type", "application/json")
            .body(SampleRequestDto.of("postJson1", "postJson2", "postJson3")).asString();

        log.info("response1 :: {}", response1.getBody());
        log.info("response2 :: {}", response2.getBody());

        return ResponseEntity.ok("test");
    }
2023-08-30 17:51:02.730  INFO 50225 --- [nio-8080-exec-1] t.b.h.s.c.SampleRequestController        : response1 :: {"timestamp":"2023-08-30T08:51:02.668+00:00","status":400,"error":"Bad Request","path":"/api/v1/post1"}
2023-08-30 17:51:02.730  INFO 50225 --- [nio-8080-exec-1] t.b.h.s.c.SampleRequestController        : response2 :: Hello! Post!

Expected behavior It expects http to be called normally.

Environmental Data:

Additional context I think it's a bug caused by creating HttpRequest<?> with different field() Method or body() Method. field() returns MultipartBody, body() returns RequestBodyEntity Please confirm.

ryber commented 10 months ago

I don't understand what you are trying to do? the example code doesn't use the field(,) method.

You also cannot use field with a body of "application/json" because it is explicitly for multipart forms and url-encoded bodies and is NOT json

ryber commented 10 months ago

oooh I see, those methods are immutable, so you need to reassign it:

HttpRequestWithBody request = Unirest.request("POST", "http://localhost:8080/api/v1/post1");
 request =       request.header("Content-Type", "application/json");
 request =      request.body(SampleRequestDto.of("postJson1", "postJson2", "postJson3"));
BBackJK commented 10 months ago

Thank you for your reply. I may not have checked the document properly. I will refer to it and do nice coding. thank you