#region 构造URL POST请求
/// <summary>
/// 获取请求的反馈信息
/// </summary>
/// <param name="url">请求URL</param>
/// <param name="bData">参数字节数组</param>
/// <returns>响应内容</returns>
private static String doPostRequest(string url, byte[] bData)
{
HttpWebRequest hwRequest;
HttpWebResponse hwResponse;
string strResult = string.Empty;
//.net(客户端)调用php(服务端)出现417错误
try
{
ServicePointManager.Expect100Continue = false;//远程服务器返回错误: (417) Expectation failed 异常源自HTTP1.1协议的一个规范: 100(Continue)
hwRequest = (HttpWebRequest)WebRequest.Create(url);
hwRequest.Timeout = 2000;
hwRequest.Method = "POST";
hwRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
hwRequest.ContentLength = bData.Length;
Stream smWrite = hwRequest.GetRequestStream();
smWrite.Write(bData, 0, bData.Length);
smWrite.Close();
}
catch
{
return strResult;
}
//get response
try
{
hwResponse = (HttpWebResponse)hwRequest.GetResponse();
StreamReader srReader = new StreamReader(hwResponse.GetResponseStream(), Encoding.UTF8);
strResult = srReader.ReadToEnd();
srReader.Close();
hwResponse.Close();
}
catch
{
return strResult;
}
return strResult;
}
#endregion
#region POST请求
/// <summary>
/// 发送请求
/// </summary>
/// <param name="url">请求URL</param>
/// <param name="param">参数字符串</param>
/// <returns>响应内容</returns>
public static string PostMethod(string url, string param)
{
byte[] data = Encoding.UTF8.GetBytes(param);
return doPostRequest(url, data);
}
#endregion
调用 string value=PostMethod("http://www.csdn.net/","username=aaa&password=bbbbb");
if(value==""){
Responese.Write("空值");
} else{
Response.Write(value);
}