C# 通过HttpWebRequest来调用webApi接口数据

5 篇文章 0 订阅

 

1、定义传输协议 

public enum HttpType
    {
        POST,
        GET,
        DELETE
    }

 2、访问代码

 
    public static class HttpRequestManager
    {

        public static void HttpRespons(string url, HttpType httpType, string contenType, Action<string> _successCallBack = null, string token = null, Action _failCallBack = null)
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = httpType.ToString();
                request.ContentType = contenType;
                if (token != null)
                {
                    request.Headers.Add("Authorization", "Bearer " + token);
                }
                var httpResponse = (HttpWebResponse)request.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                    _successCallBack?.Invoke(result);
                }
            }
            catch
            {
                _failCallBack?.Invoke();
            }
        }
    }

3、调用

    HttpRequestManager.HttpRespons("http://baidu.com/Api/Account/User/AccessToken?LoginId=" + userAccrout + "&Password=" + userPassword + "&Expiration=1200", HttpType.GET, "text/json", delegate (string resule)
            {
                JObject jsonObj = JObject.Parse(resule);
           
                if (jsonObj["name"].ToString().Contains("name"))
                {
                 
                  string  Token = jsonObj["token"].ToString();
                }
                else
                {
                    
                    MessageBox.Show("账号权限不匹配", "登陆失败");
                }
            }, null, () => {  MessageBox.Show("账号密码错误", "登陆失败"); });

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的用C#和.Net框架实现调用WebApi接口并解析响应数据的示例: ```csharp using System; using System.IO; using System.Net; using System.Text; using Newtonsoft.Json; class Program { static void Main(string[] args) { string url = "http://example.com/api/data"; // WebApi接口地址 string postData = "{\"name\": \"John\", \"age\": 30}"; // POST数据(JSON格式) try { // 创建Web请求对象 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json"; request.Timeout = 10000; // 设置超时时间 // 将POST数据写入请求流中 byte[] postDataBytes = Encoding.UTF8.GetBytes(postData); request.ContentLength = postDataBytes.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(postDataBytes, 0, postDataBytes.Length); } // 发送Web请求并获取响应 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { // 解析响应数据 using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); string responseText = reader.ReadToEnd(); dynamic responseData = JsonConvert.DeserializeObject(responseText); Console.WriteLine(responseData); } } } catch (WebException ex) { // 处理Web请求异常 Console.WriteLine(ex.Message); } catch (Exception ex) { // 处理其他异常 Console.WriteLine(ex.Message); } Console.ReadLine(); } } ``` 在上面的示例中,我们首先定义了一个WebApi接口地址和要发送的POST数据(JSON格式)。然后,我们使用HttpWebRequest类创建一个POST请求,并将POST数据写入请求流中。最后,我们将请求发送到WebApi接口,并使用HttpWebResponse类获取响应数据。在获取到响应数据后,我们使用JsonConvert类将JSON格式的响应数据转换为动态对象,以便我们可以轻松地访问其属性。最后,我们将响应数据打印到控制台上。如果出现任何异常,我们将其打印到控制台上以便调试。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值