hamza saber
hamza saber

Reputation: 569

Spring WebClient Post method Body

i'm trying to send a POST request with body data as described here: https://scrapyrt.readthedocs.io/en/stable/api.html#post.

Here's what i've tried to do but it gives me HTTP code 500

String uri = "http://localhost:3000";

WebClient webClient = WebClient.builder()  
            .baseUrl(uri)
            .build();
LinkedMultiValueMap map = new LinkedMultiValueMap();

        String q = "\"url\": \"https://blog.trendmicro.com/trendlabs-security-intelligence\",\"meta\":{\"latestDate\" : \"18-05-2020\"}}";
        map.add("request", q);
        map.add("spider_name", "blog");

        BodyInserter<MultiValueMap<String, Object>, ClientHttpRequest> inserter2
         = BodyInserters.fromMultipartData(map);

        Mono<ItemsList> result = webClient.post()
                                          .uri(uriBuilder -> uriBuilder
                                                           .path("/crawl.json")
                                                           .build())
                                          .body(inserter2)
                                          .retrieve()
                                          .bodyToMono(ItemsList.class);

        ItemsList tempItems = result.block();

Upvotes: 8

Views: 50662

Answers (2)

Ravikumar Kumarasamy
Ravikumar Kumarasamy

Reputation: 59

For me following code worked:

public String wcPost(){

    Map<String, String> bodyMap = new HashMap();
    bodyMap.put("key1","value1");
 

    WebClient client = WebClient.builder()
            .baseUrl("domainURL")
            .build();


    String responseSpec = client.post()
            .uri("URI")
            .headers(h -> h.setBearerAuth("token if any"))
            .body(BodyInserters.fromValue(bodyMap))
            .exchange()
            .flatMap(clientResponse -> {
                if (clientResponse.statusCode().is5xxServerError()) {
                    clientResponse.body((clientHttpResponse, context) -> {
                        return clientHttpResponse.getBody();
                    });
                    return clientResponse.bodyToMono(String.class);
                }
                else
                    return clientResponse.bodyToMono(String.class);
            })
            .block();

    return responseSpec;
}

Upvotes: 2

Michael Berry
Michael Berry

Reputation: 72379

Here's what i've tried to do but it gives me HTTP code 500

Most likely because you're sending the wrong data in a mixture of wrong formats with the wrong type:

  • You're using multipart form data, not JSON
  • You're then setting the request parameter as a JSON string (q)
  • The JSON string you're using in q isn't even valid (it's at least missing an opening curly brace) - and handwriting JSON is almost universally a bad idea, leverage a framework to do it for you instead.

Instead, the normal thing to do would be to create a POJO structure that maps to your request, so:

public class CrawlRequest {

    private CrawlInnerRequest request;
    @JsonProperty("spider_name")
    private String spiderName;

    //....add the getters / setters
}

public class CrawlInnerRequest {

    private String url;
    private String callback;
    @JsonProperty("dont_filter")
    private String dontFilter;

    //....add the getters / setters
}

...then simply create a CrawlRequest, set the values as you wish, then in your post call use:

.body(BodyInserters.fromValue(crawlRequest))

This is a rather fundamental, basic part of using a WebClient. I'd suggest reading around more widely to give yourself a better understanding of the fundamentals, it will help tremendously in the long run.

Upvotes: 14

Related Questions