C#怎样通过url调用接口
展开全部
web 接口,常用的请求方式有两种
GET
POST
public static class Http
{
private static Encoding GetEncoding(HttpWebResponse response)
{
var encodingText = response.ContentEncoding;
if (string.IsNullOrEmpty(encodingText))
encodingText = "UTF-8";
return Encoding.GetEncoding(encodingText);
}
private static string JoinParam(IDictionary<string, string> input)
{
var sb = new StringBuilder();
using (var e = input.GetEnumerator())
{
if (e.MoveNext())
{
var key = HttpUtility.UrlEncode(e.Current.Key);
var value = HttpUtility.UrlEncode(e.Current.Value);
sb.AppendFormat("{0}={1}", key, value);
while (e.MoveNext())
{
key = HttpUtility.UrlEncode(e.Current.Key);
value = HttpUtility.UrlEncode(e.Current.Value);
sb.AppendFormat("&{0}={1}", key, value);
}
}
}
return sb.ToString();
}
public static string PostStream(string url, IDictionary<string, string> header = null, Stream stream = null, Encoding encoding = null)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Post;
if (header != null)
{
foreach (var key in header.Keys)
{
var value = header[key];
switch (key)
{
case "Content-Type":
request.ContentType = value;
break;
case "Content-Length":
request.ContentLength = Convert.ToInt64(value);
break;
default:
request.Headers.Set(key, value);
break;
}
}
}
if (stream != null)
{
request.ContentLength = stream.Length;
using (var rStream = request.GetRequestStream())
{
stream.CopyTo(rStream);
}
}
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var rStream = response.GetResponseStream())
{
if (encoding == null)
{
encoding = GetEncoding(response);
}
using (var reader = new StreamReader(rStream, encoding))
return reader.ReadToEnd();
}
}
}
public static string Post(string url, IDictionary<string, string> header = null, IDictionary<string, string> input = null)
{
Stream dst = null;
if (input != null)
{
var str = JoinParam(input);
var bytes = Encoding.UTF8.GetBytes(str);
dst = new MemoryStream(bytes);
}
var result = PostStream(url, header, dst);
dst?.Dispose();
return result;
}
public static string Get(string url, IDictionary<string, string> header = null, IDictionary<string, string> input = null)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Get;
if (header != null)
{
foreach (var key in header.Keys)
request.Headers[key] = header[key];
}
if (input != null)
{
url += "?" + JoinParam(input);
}
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var rStream = response.GetResponseStream())
{
var encoding = GetEncoding(response);
using (var reader = new StreamReader(rStream, encoding))
return reader.ReadToEnd();
}
}
}
}
提供了两种方式的请求实现。
示例:
var kvParam = new Dictionary<string, string>();
kvParam["name"] = "xxx";
kvParam["password"] = "xxx";
var result = Http.Post("http://www.xxx.com/login.php", null, kvParam);
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询