Ivan S
Ivan S

Reputation: 1081

Set a body for WebClient when making a Post Request

So I have an api that I want to call to. The first call is an ahoy call and in the body of the request I need to send the ship_type, piratename and my piratepass. I then want to read the response which has my treasure booty that i will use for later.

I'm able to do this with web request. but i feel like there is a better way to do it with webclient.

(way I currently do it in webrequest)

        //Credentials for the Pirate api
        string piratename = "IvanTheTerrible";
        string piratepass= "YARRRRRRRR";

        string URI = "https://www.PiratesSuperSecretHQ.com/sandyShores/api/respectmyauthority";

        WebRequest wr = WebRequest.Create(URI);

        wr.Method = "POST";
        wr.ContentType = "application/x-www-form-urlencoded";

        string bodyData = "ship_type=BattleCruiser&piratename=" + piratename + "&piratepass=" + piratepass;

        ASCIIEncoding encoder = new ASCIIEncoding();

        byte[] byte1 = encoder.GetBytes(bodyData);

        wr.ContentLength = byte1.Length;
        //writes the body to the request
        Stream newStream = wr.GetRequestStream();

        newStream.Write(byte1, 0, byte1.Length);
        newStream.Close();            

        WebResponse wrep = wr.GetResponse();

        string result;

        using (var reader = new StreamReader(wrep.GetResponseStream()))
        {
            result = reader.ReadToEnd(); // do something fun...
        }

Thanks in advance either way.

Upvotes: 9

Views: 36369

Answers (2)

Ravikumar Kumarasamy
Ravikumar Kumarasamy

Reputation: 59

You can try like below as well:

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

Glauco Cucchiar
Glauco Cucchiar

Reputation: 774

You can do with this simple code

Uri uri = new Uri("yourUri");
string data = "yourData";

WebClient client = new WebClient();
var result = client.UploadString(uri, data);

Remember that you can use UploadStringTaskAsync if you want to be async

Upvotes: 22

Related Questions