C# 访问Api接口
class HttpPost
{
public static string Request(string url, string data)
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytesToPost = encoding.GetBytes(data); //转换为bytes数据
string responseResult = String.Empty;
HttpWebRequest req = null;
HttpWebResponse cnblogsRespone = null;
try
{
req = (HttpWebRequest)
HttpWebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
req.ContentLength = bytesToPost.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bytesToPost, 0, bytesToPost.Length);
}
cnblogsRespone = (HttpWebResponse)req.GetResponse();
if (cnblogsRespone != null && cnblogsRespone.StatusCode == HttpStatusCode.OK)
{
StreamReader sr;
using (sr = new StreamReader(cnblogsRespone.GetResponseStream()))
{
responseResult = sr.ReadToEnd();
}
sr.Close();
}
return responseResult;
}
catch(Exception ex)
{
return null;
}
finally
{
cnblogsRespone.Close();
}
}
}
实现小小的助手方法,帮助构造第二个参数 data, 简化工作
public static string ConvertParameter(Dictionary<string, string> dict)
{
string s = "";
foreach (var item in dict.Keys)
{
s += (item + "=" + dict[item]).ToString();
s += "&";
}
return s.Substring(0, s.Length - 1);
}
实际使用
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add(key, value);
string post_result = HttpPost.Request("http://127.0.0.1/**", ConvertParameter(dict));
以上经过 多次测试,正式运用于项目中,做个记录,方便后续开发,也希望给您带来帮助!