C#POST 支付宝/微信回调接口

一般支付宝/微信的回调接口都会返回xml格式,下面是调用类似这种接口的办法:


public async Task<string> GetData()
{
            string requestUrl = "http://localhost:xxx/xx/xxxx/xxx/xxxx";//请求的接口URL
            string contentType = "application/x-www-form-urlencoded";//请求文本类型
            string result = string.Empty;//返回结果,xml格式的字符串
            using (var client = new HttpClient())
            {
                object data = null;
                string str = JsonHelper.Instance.Serialize(data);//一般这种接口的请求参数都是空的,也就是不需要请求参数
                var content = new StringContent(str)
                {
                    Headers = { ContentType = new MediaTypeHeaderValue(contentType) }
                };
                HttpResponseMessage resp = await client.PostAsync(requestUrl, content);
                resp.EnsureSuccessStatusCode();//返回http响应状态码

                result = resp.Content.ReadAsStringAsync().Result;//<xml><return_code><![CDATA[{0}]]></return_code><return_msg><![CDATA[{1}]]></return_msg></xml>

                return result;
            }
}

下面介绍基本接口POST的办法,文本格式一般是JSON格式去请求:

public async Task<Result> GetData()
{
            string requestUrl = "http://xxxxxxxx/xxxx/xxx/xxx/xxx";//请求的接口URL
            string signData = "lrfVUpo8uCHvhPXEd6PsUH82XEkc+kUyQYDssRlop1AcbY5WXH0kWAWhAioQCwl5N+lZGDijqH67aaBcICa7LJOAN1r7z0H8ghNKOROW2ugGX6x7dZKeZA0GmfJsuNK30eONDu6GdTTnZGgEJsPepxh/AIFJZYdN6RVseIDJAwQ=";
            string data = "eyJJc1N1Y2Nlc3MiOnRydWUsIkNvZGUiOiIwMDUyMDE4MTAyNDI1NDkyODIiLCJEZXNjcmlwdGlvbiI6IuaTjeS9nOaIkOWKnyJ9";
            object obj = new { SignData = signData, Data = data };//使用匿名类构造object
            string result = string.Empty;
            using (var client = new HttpClient())
            {
                string str = JsonHelper.Instance.Serialize(obj);
                var content = new StringContent(str)
                {
                    Headers = { ContentType = new MediaTypeHeaderValue("Application/json") }
                };
                HttpResponseMessage resp = await client.PostAsync(requestUrl, content);

                if (resp.IsSuccessStatusCode)
                {
                    result = resp.Content.ReadAsStringAsync().Result;
                }

                return JsonHelper.Instance.Deserialize<Result>(result);//这里返回的是字符串,JSON格式数据
            }            
}

后续可以序列化字符串为对象

C#POST 支付宝/微信回调接口

上一篇:仿微信未读RecyclerView平滑滚动定位效果


下一篇:手机、电脑、安卓、iOS、微信浏览器判断