winfrom 利用HttpWebRequest 访问接口
贴上代码
Encoding encoding = Encoding.GetEncoding("utf-8");
string postData = "username="+u.UserId+"&password="+u.UserPwd;
//"{'username':'" + u.UserId + "','password':'" + u.UserPwd + "'}";
string strUrl = url;
byte[] data = encoding.GetBytes(postData);
// 准备请求...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(strUrl);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
// 发送数据
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse res = myRequest.GetResponse() as HttpWebResponse;
StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding("utf-8"));
string result = sr.ReadToEnd();
//接收的返回数据
sr.Close();
res.Close();