最近在学习三种调用接口方式,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;
}
}
新闻热点
疑难解答