• HttpClient.PostAsynct 发送Json数据


    HttpClient.PostAsync第二个参数设置HttpContent 发送Json数据。

    需要这是这个content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

    如果这是这样 : client.DefaultRequestHeaders.Add("ContentType", "application/json"); 设置去请求有时候会不成功,服务端不认。说你mediaType不正确。

     public async static Task<string> SendRequest(string url, string data)
            {
                var responseJson = "";
                var client = new HttpClient();
                try
                {
                    client.Timeout = new TimeSpan(1, 0, 0, 0, 0);
                    client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
                    client.DefaultRequestHeaders.Add("Keep-Alive", "timeout=600");
                    client.DefaultRequestHeaders.Add("ContentType", "application/json");
                    client.DefaultRequestHeaders.Add("Accept", "*/*");
       
                   HttpContent content = new StringContent(data);
                   content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    var Result =await  client.PostAsync(url, content);
                    if (Result.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        responseJson = await Result.Content.ReadAsStringAsync();
                    }
                    else
                    {
                        throw new Exception("Request Url is " + url+ " Response is " + Result.StatusCode);
                    }
                    if (string.IsNullOrEmpty(responseJson))
                    {
                        throw new Exception("Request Url is " + url + " Response is " + Result.StatusCode);
                    }
                }
                catch (Exception ex)
                {
                    throw;
                }
                finally
                {
                    client.Dispose();
                }
                return await Task.FromResult(responseJson);
            }
    

      

     
     
  • 相关阅读:
    Bluedroid介绍
    Android蓝牙介绍
    Android Bluetooth抓包
    Bluetooth LMP介绍
    Bluetooth Baseband介绍
    Bluetooth SDP介绍
    Bluetooth HFP介绍
    Bluetooth RFCOMM介绍
    Bluetooth L2CAP介绍
    Windows开发
  • 原文地址:https://www.cnblogs.com/wgscd/p/12766296.html
Copyright © 2020-2023  润新知