HttpClient 简单使用 学习记录

坑:1 同步也异步问题;2 乱码问题 ;3 参数问题

HttpClient 作为发送方传递参数时,接收方为WebApi,此时有多种接收方法

1:直接用实体接收,适用于多参数

2:用System.Web.HttpContext.Current.Request.QueryString[“参数名”].ToString();来接收

下面是接收方的代码:

using System.Web.Http;
using System.Web.Http.Cors;

namespace WebApplication1.Controllers
{
    [EnableCors("*", "*", "GET, POST, PUT, DELETE, OPTIONS")]
    public class HomeController : ApiController
    {
        [HttpGet,Route("api/Home/Get")]
        public IHttpActionResult Get(string name)
        {
            return Ok(name);
        }

        [HttpPost, Route("api/Home/Post")]
        public IHttpActionResult Post([FromBody]  model model)
        {
            return Ok(model.name);
        }

        public static string GetRequsetForm(string key, string defaultVal)
        {
            if (System.Web.HttpContext.Current.Request.Form[key] == null)
                return defaultVal;
            return System.Web.HttpContext.Current.Request.Form[key].ToString();
        }
        public static string GetRequsetQueryString(string key, string defaultVal)
        {
            if (System.Web.HttpContext.Current.Request.QueryString[key] == null)
                return defaultVal;
            return System.Web.HttpContext.Current.Request.QueryString[key].ToString();
        }
    }
    public class model
    {
        public string name { get; set; }
    }
}

下面是HttpClient代码,只是简单的实现功能,并没有进行封装

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;

namespace TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Get();
        }
        
       
        private static async void GetAsync()
        {
            HttpClient httpClient = new HttpClient();
            httpClient.BaseAddress = new System.Uri("http://localhost:6942/api/Home/Post");
            
            try
            {
                HttpResponseMessage response = await httpClient.GetAsync("?name='你好'&age='12'");
                response.EnsureSuccessStatusCode();
                string resultStr = await response.Content.ReadAsStringAsync();
                Console.WriteLine(resultStr);
            }
            catch (Exception ex)
            {
                throw;
            }
            // 创建一个异步GET请求,当请求返回时继续处理(Continue-With模式)  
           
        }

        private static void Get()
        {
            HttpClient httpClient = new HttpClient();

            httpClient.BaseAddress = new System.Uri("http://localhost:6942/api/Home/Get");

            HttpResponseMessage response = httpClient.GetAsync("?name=你好&age=12").Result;
            response.EnsureSuccessStatusCode();
            string resultStr = response.Content.ReadAsStringAsync().Result;
            var str = JsonConvert.DeserializeObject(resultStr);
            Console.OutputEncoding = Encoding.UTF8;
            Console.WriteLine(str);
        }

        private static void Post()
        {
            string Uri = "http://localhost:6942/api/Home/Post";
            HttpClient httpClient = new HttpClient();
            HttpContent postContent = new FormUrlEncodedContent(new Dictionary<string, string>()
            {
               {"name", "dong"}
            }); 
            HttpResponseMessage response = httpClient.PostAsync(Uri,postContent).Result;
            response.EnsureSuccessStatusCode();
            string resultStr = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine(resultStr);
        }
    }
}

 

转载于:https://my.oschina.net/u/3641517/blog/1544025

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值