C#调用WebApi(Get、Post、Delete、Put)

Get

public static string GetData(string url)
{
     HttpClient httpClient = new HttpClient();
     return httpClient.GetStringAsync(url).Result;
 }

Get(带参请求)

/// <summary>
/// Get请求
/// </summary>
/// <param name="url">地址</param>
/// <param name="dic">请求参数定义</param>
/// <returns></returns>
private static string GetDataRequest(Dictionary<string, object> dic, string url)
{
    string result = string.Empty;
    StringBuilder builder = new StringBuilder();
    builder.Append(url);
    if (dic.Count > 0)
    {
        builder.Append("?");
        int i = 0;
        foreach (var item in dic)
        {
            if (i > 0)
                builder.Append("&");
            builder.AppendFormat("{0}={1}", item.Key, item.Value);
            i++;
        }
    }
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(builder.ToString());
    //设置请求头(本例使用Ouath2获取token,在redis上获取,不设置的可以不看下面两行的代码)
    ServiceStack.Redis.RedisClient cache = new ServiceStack.Redis.RedisClient("127.0.0.1", 6379, "password");
    SetHeaderValue(req.Headers, "Token", cache.Get<string>("token"));
    //添加参数
    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
    Stream stream = resp.GetResponseStream();
    try
    {
        //获取内容
        using (StreamReader reader = new StreamReader(stream))
        {
            result = reader.ReadToEnd();
        }
    }
    finally
    {
        stream.Close();
    }
    return result;
}

/// <summary>
/// 设置请求头
/// </summary>
/// <param name="name">参数名</param>
/// <param name="value">参数值</param>
private static void SetHeaderValue(WebHeaderCollection header, string name, string value)
{
    var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.Instance | BindingFlags.NonPublic);
    if (property != null)
    {
        var collection = property.GetValue(header, null) as NameValueCollection;
        collection[name] = value;
    }
}

Post、Delete、Put

public static string PostData(string data, string uri)
{
    return CommonHttpWebRequest(data, uri, "POST");
}

public static string PutData(string data, string uri)
{
    return CommonHttpWebRequest(data, uri, "PUT");
}

public static string DeleteData(string data, string uri)
{
    return CommonHttpWebRequest(data, uri, "DELETE");
}


//HttpWebRequest通用方法
private static string CommonHttpWebRequest(string data, string uri, string type)
{
	//构造http请求的对象
	HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
	//转成流
	byte[] buffer = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
	//请求设置
	request.Method = type;
	request.ContentLength = buffer.Length;
	//request.ContentType = "application/...";//设置参数格式,入参一定要与参数格式相对应
	request.ContentType = "application/json";
	request.MaximumAutomaticRedirections = 1;
	request.AllowAutoRedirect = true;
	// 发送请求
	Stream newStream = request.GetRequestStream();
	newStream.Write(buffer, 0, buffer.Length);
	newStream.Close();
	// 获得接口返回值
	HttpWebResponse response;
	try
	{
	    response = (HttpWebResponse)request.GetResponse();
	}
	catch (WebException ex)
	{
	    response = (HttpWebResponse)ex.Response;
	}
	StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
	string result = streamReader.ReadToEnd();
	streamReader.Close();
	response.Close();
	return result;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值