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;
}