使用HttpClient发送数据 到WebApi

Posted 闲莫等

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用HttpClient发送数据 到WebApi相关的知识,希望对你有一定的参考价值。

发送和JSON数据

/=============================webAPI接受POST的JOSN数据=============================/
 POST api/<controller>
[HttpPost]
public string Post([FromBody]string value)
{
    var requestContent = value;
    var result = "[{\"name\":\"12\"}]";
    return result;
}


// 发送方法
public void SendStringToWebApi()
{
	
	#region 调用API发送字典数据

            // (orders+vehicles+appkey+timestamp+version+appsecret)
            var timestamp = DateTime.Now.ToString("yyyyMMddHHmmssSSS");
            var sign = DigitalSignature.MD5(JsonConvert.SerializeObject(listOrder) + appkey + timestamp + "1" + appsecret);
            var qid = timestamp + sign;

            var url = "http://www.routeapi.com/api/Order";
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };

            using (var http = new HttpClient(handler))
            {
                // 发送的JSON数据
                var _TrasnTask = new TrasnTask()
                {
                    Orders = listOrder,
                    appkey = appkey,
                    timestamp = timestamp,
                    version = "1",
                    sign = sign
                };
                var postJsonContent = JsonConvert.SerializeObject(_TrasnTask);

                http.DefaultRequestHeaders.Accept.Clear();

                // 指定提交的数据格式
                // http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                // HttpResponseMessage response;
                // var action = Uri.EscapeUriString(url);

                //Obj is passed into this, currently it is of type File 
                // var content = new StringContent(postJsonContent, Encoding.UTF8, "application/json");

                // response = http.PostAsync(action, content).Result;
                response = http.PostAsJsonAsync<string>(url, postJsonContent).Result;
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = response.Content;
                    string responseString = responseContent.ReadAsStringAsync().Result;
                    TempData["responseLocation"] = responseString;
                }
            }

}

 

发送字段数据

public void SendDicToWebApi()
{
     //// (orders+vehicles+appkey+timestamp+version+appsecret)
            //var timestamp = DateTime.Now.ToString("yyyyMMddHHmmssSSS");
            //var sign = DigitalSignature.MD5(JsonConvert.SerializeObject(listOrder) + appkey + timestamp + "1" + appsecret);
            //var qid = timestamp + sign;

            //var url = "http://www.routeapi.com/api/Order/PostToDic";
            //var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };

            //using (var http = new HttpClient(handler))
            //{
            //    var formDic = new Dictionary<string, string>()
            //    {
            //        {"orders",JsonConvert.SerializeObject(listOrder)},
            //        {"vehicles","vehiclesVlaues"},
            //        {"appkey",appkey},
            //        {"timestamp",timestamp},
            //        {"version","1"},
            //        {"sign",sign}
            //    };

            //    var content = new FormUrlEncodedContent(formDic);

            //    // 发送字典集合
            //    var response = http.PostAsync(url, content).Result; 

            //    // 接受返回值
            //    var httpStatusCode = response.IsSuccessStatusCode;
            //    var responseLocation = response.Headers.Location;
            //    TempData["responseLocation"] = response.Content.ToString();

            //}



///// <summary>
        ///// 接受普通文本
        ///// </summary>
        ///// <param name="value"></param>
        ///// <returns></returns>
        //[HttpPost]
        //// public string Post([FromBody]string value)
        //public string PostToDic(FormDataCollection value)
        //{
        //    var orders_1 = value.GetValues("orders");
        //    return "文本已经接受到了";

        //    ///// 接受地址栏的参数
        //    //var requestUri = Request.RequestUri.ParseQueryString();
        //    //var orders = requestUri["orders"];
        //    //var vehicles = requestUri["vehicles"];
        //    //var appkey = requestUri["appkey"];
        //    //var timestamp = requestUri["timestamp"];
        //    //var version = requestUri["version"];
        //    //var sign = requestUri["sign"];
        //}

}

 

以上是关于使用HttpClient发送数据 到WebApi的主要内容,如果未能解决你的问题,请参考以下文章

.NET WebApi HttpClient 未将 Windows 身份验证凭据发送到同一域

从 HttpClient 向 webapi 提交 File 和 Json 数据

HttpClient 与 HttpWebRequest

在 HttpClient 中解压 Brotli HttpResponse

利用HttpClient调用WebApi

使用 HttpClient 发送 MultipartFormDataContent 时设置 ContentType 标头