首页 > 学院 > 开发设计 > 正文

本地测试IIS,Post调用接口

2019-11-14 15:52:32
字体:
来源:转载
供稿:网友

最近在学习三种调用接口方式,POST,Socket,Webserivce,今天刚写完POST方式所以就分享下,欢迎高手指点。

public string strResult = "";
PRotected void Page_Load(object sender, EventArgs e)
{
MyResponseList("发送是否成功");
}
public void MyResponseList(string Charset)
{


try
{
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byteArray = encoding.GetBytes(Charset);
//入口地址 可以传参数
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri("http://192.168.16.39:808/Default.aspx?num=3&&name=broueli"));
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.ContentLength = byteArray.Length;

//获取请求对象
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);//写入参数
newStream.Close();
//返回Internet响应
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
string encod = response.ContentEncoding;

//判断是否获取到编码方式
if (encod == null || encod.Length < 1)
{
encod = "UTF-8";
}
//读取流,该流用于读取来自服务器响应体,Encoding 可以直接定义也可以获取
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encod));
//从流的当前位置读取到末尾
strResult = sr.ReadToEnd();
sr.Close();
response.Close();
newStream.Close();

}
catch (Exception exp)
{

strResult = "错误:" + exp.Message;

}
}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表