繁体   English   中英

发出 Post 请求时为 WebClient 设置正文

[英]Set a body for WebClient when making a Post Request

所以我有一个我想调用的 api。 第一个调用是 ahoy 调用,在请求正文中,我需要发送 ship_type、piratename 和我的海盗通行证。 然后,我想阅读包含我将在以后使用的宝藏的回复。

我可以通过网络请求来做到这一点。 但我觉得用 webclient 有更好的方法来做到这一点。

(我目前在 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...
        }

提前致谢。

你可以用这个简单的代码

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

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

请记住,如果您想要异步,可以使用UploadStringTaskAsync

您也可以尝试如下:

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM