【C#】HTTP请求通讯实现

1.Post请求

/// <summary>
/// HTTP POST请求
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="value">参数</param>
/// <param name="timeout">超时时间,默认5秒</param>
/// <returns></returns>
public JObject Post(string url, string value, int timeout = 10)
{
    JObject result = new JObject();
    result["code"] = 99;
    result["message"] = "请求失败";
    try
    {
        HttpClient client = new HttpClient();
        HttpContent content = new StringContent(value);
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        // 数据转化为 key=val 格式
        //var content =  new FormUrlEncodedContent(value);
        //默认希望响应使用Json序列化(内容协商机制,我接受json格式的数据)
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.Timeout = new TimeSpan(0, 0, timeout);
        // 发送请求
        var response = client.PostAsync(url, content);
        // 获取数据
        string message = response.Result.Content.ReadAsStringAsync().Result.ToString();
        result["code"] = 0;
        result["message"] = message;
    }
    catch (Exception ex)
    {
        result["code"] = 1;
    }
    return result;
}

2.Get请求

/// <summary>
/// HTTP Get请求
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="timeout">超时时间,默认5秒</param>
/// <returns></returns>
public JObject Get(string url, int timeout = 10)
{
    JObject result = new JObject();
    result["code"] = 99;
    result["message"] = "请求失败";
    try
    {
        HttpClient client = new HttpClient();
        client.Timeout = new TimeSpan(0, 0, timeout);
        // 发送请求
        var response = client.GetAsync(url);
        // 获取数据
        string message = response.Result.Content.ReadAsStringAsync().ToString();
        result["code"] = 0;
        result["message"] = message;
    }
    catch (Exception ex)
    {
        result["code"] = 1;
    }
    return result;
}

3.DELETE请求

/// <summary>
/// HTTP DELETE请求
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="timeout">超时时间,默认5秒</param>
/// <returns></returns>
public JObject Delete(string url, int timeout = 10)
{
    JObject result = new JObject();
    result["code"] = 99;
    result["message"] = "请求失败";
    try
    {
        HttpClient client = new HttpClient();
        client.Timeout = new TimeSpan(0, 0, timeout);
        // 发送请求
        var response = client.DeleteAsync(url);
        // 获取数据
        string message = response.Result.Content.ReadAsStringAsync().ToString();
        LogHelperUtility.Info(string.Format("[Delete]请求返回参数:{0}", message));
        result["code"] = 0;
        result["message"] = message;
    }
    catch (Exception ex)
    {
        result["code"] = 1;
    }
    return result;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值