1、HttpWebRequest对象和HttpWebResponse对象的使用。
使用HttpWebRequest配合StreamWriter发送数据;使用HttpWebRespose配合StreamReader接收数据。
发送数据的代码:
private System.Net.HttpWebResponse GetResponse(string postData)
{
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(c_posturl);
webrequest.Method = "POST";
webrequest.UserAgent = "VUO Domain Checking Agent.";
webrequest.ContentType = "application/x-www-form-urlencoded";
webrequest.AllowAutoRedirect = false;
webrequest.ContentLength = postData.Length;
using(StreamWriter write = new StreamWriter(webrequest.GetRequestStream())){
write.Write(postData);
write.Close();
}
try
{
return (HttpWebResponse)webrequest.GetResponse();
}
catch(Exception ex)
{
throw ex;
}
}
接收数据的代码:
private string AnalisysResponse(HttpWebResponse webresponse)
{
if (webresponse == null)
{
Response.Write("webresponse is null");
return null;
}
string result = "";
if (webresponse.StatusCode == HttpStatusCode.OK)
{
using (StreamReader reader = new StreamReader(webresponse.GetResponseStream(), System.Text.Encoding.GetEncoding(encoding)))
{
result = reader.ReadToEnd();
}
}
webresponse.Close();return result;
}
2、可能涉及MD5加密
.NET类库中的MD5API不能直接加密字符串,需要转换为byte数组操作。
MD5加密代码(32位)
private string MD5(string str)
{
byte[] bs = System.Text.Encoding.Default.GetBytes(str);
bs = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(bs);
string returnstr = "";
for (int i = 0; i < bs.Length; i++)
{
returnstr += bs[i].ToString("x").PadLeft(2, '0');
}
return returnstr;
}
3、Post数据的组织和分解
POST数据是一组Key=Value的值对使用“&”链接起来的字符串。在发送数据时要进行字符串组合并对值进行URLEncode;在接收时要对这些字符串进行拆解。我选择泛型版的Dictionary作为容器,方便查询。
需要注意的是UrlEncode也要区分编码的,可以通过设置Encoding来区分。
4、与Apache通讯的特殊性和Web.config的设置
C#向某些Apache服务提交POST请求时会遇到这样的错误:System.Net.WebException: 远程服务器返回错误: (417) Expectation Failed,解决办法是在配置文件中增加一下标记:
<configuration> <system.net> <settings> <servicePointManager expect100Continue=”false”/> </settings> </system.net> </configuration>
参考网址:
“远程服务器返回错误: (417) Expectation failed。”
C# post数据时 出现如下错误: System.Net.WebException: 远程服务器返回错误: (417) Expectation Failed 的解决办法