get/post 接口调用

时间:2022-03-16 00:35:19

content-type:  application/~~~~~

  /// <summary>
/// Post数据到网站
/// </summary>
/// <param name="posturl">网址</param>
/// <param name="postData">参数</param>
/// <returns></returns>
public static string postHTTP(string posturl, string postData)
{
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
Encoding encoding = System.Text.Encoding.GetEncoding("UTF-8");
byte[] data = encoding.GetBytes(postData);
// 准备请求...
try
{
// 设置参数
request = WebRequest.Create(posturl) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
outstream = request.GetRequestStream();
outstream.Write(data, , data.Length);
outstream.Close();
//发送请求并获取相应回应数据
response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
string err = string.Empty;
return content;
}
catch (Exception ex)
{
string err = ex.Message;
return string.Empty;
}
}

IT用语:通常这种同操作系统或其他应用程序进行交互的应用程序请求称为应用程序接口,也就是常常提起的API

当content-type:  application/json时

   string tokenJson = "";
Dictionary<string, string> par = new Dictionary<string, string>();
par.Add("account", name);
par.Add("secret", pwd);
tokenJson = Tool.Json(par);
tokenJson = Tool.Remove(tokenJson); string tokenResult = Tool.postHTTP("http://61.128.195.29:8180/bskyAPI/api/GP/GetToken", tokenJson);
JObject tokenData = JObject.Parse(tokenResult);
string token = tokenData["data"]["token"].ToString();
return token;

当content-type:  application/x-www-from-urlencode时

参数格式为:name="zzzz"&id="aaaaa"