HttpWebRequest调用接口
string strResult = "";
try
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://testapi.wzeye.cn/connect/token");
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
string paraUrlCoded = System.Web.HttpUtility.UrlEncode("scope");
paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(tokenscope);
paraUrlCoded += "&" + System.Web.HttpUtility.UrlEncode("grant_type");
paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(tokengranttype);
paraUrlCoded += "&" + System.Web.HttpUtility.UrlEncode("client_id");
paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(tokenclientid);
paraUrlCoded += "&" + System.Web.HttpUtility.UrlEncode("client_secret");
paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(tokenclientsecret);
try
{
byte[] payload;
//将URL编码后的字符串转化为字节
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
//设置请求的 ContentLength
myRequest.ContentLength = payload.Length;
// 获得请 求流
Stream writer = myRequest.GetRequestStream();
//将请求参数写入流
writer.Write(payload, 0, payload.Length);
// 关闭请求流
writer.Close();
System.Net.HttpWebResponse response;
// 获得响应流
response = (System.Net.HttpWebResponse)myRequest.GetResponse();
System.IO.Stream myStream;
myStream = response.GetResponseStream();
//HttpWebResponse HttpWResp = (HttpWebResponse)myRequest.GetResponse();
//Stream myStream = HttpWResp.GetResponseStream();
StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
StringBuilder strBuilder = new StringBuilder();
while (-1 != sr.Peek())
{
strBuilder.Append(sr.ReadLine());
}
strResult = strBuilder.ToString();
}
catch (Exception exp)
{
strResult = "错误:" + exp.Message;
}
}
catch (Exception exp)
{
strResult = "错误:" + exp.Message;
}
return strResult;