接受请求的网站是GBK编码,Http Post请求参数也需要用GBK编码,以下是一段代码示例
String sResult
=
""
;
Encoding myEncoding = Encoding.GetEncoding( " GBK " );
string param = HttpUtility.UrlEncode( " merId " , myEncoding) + " = " + HttpUtility.UrlEncode(merId, myEncoding)
+ " & " + HttpUtility.UrlEncode( " merDate " , myEncoding) + " = " + HttpUtility.UrlEncode(merDate, myEncoding)
+ " & " + HttpUtility.UrlEncode( " merSeqId " , myEncoding) + " = " + HttpUtility.UrlEncode(merSeqId, myEncoding)
+ " & " + HttpUtility.UrlEncode( " version " , myEncoding) + " = " + HttpUtility.UrlEncode(version, myEncoding)
+ " & " + HttpUtility.UrlEncode( " chkValue " , myEncoding) + " = " + HttpUtility.UrlEncode(sbValue.ToString(), myEncoding);
byte [] postBytes = Encoding.ASCII.GetBytes(param);
try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create( " 请求地址 " );
req.Method = " POST " ;
req.ContentType = " application/x-www-form-urlencoded;charset=GBK " ;
req.ContentLength = postBytes.Length;
Stream webStream = req.GetRequestStream(); // 发送数据
webStream.Write(postBytes, 0 , postBytes.Length);
webStream.Close();
// 获取返回数据
HttpWebResponse webResponse = (HttpWebResponse)req.GetResponse();
StreamReader reader = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding( " GBK " ));
sResult = reader.ReadToEnd();
sResult.Trim();
}
catch (Exception e)
{
sResult = "" ;
return sResult;
}
Encoding myEncoding = Encoding.GetEncoding( " GBK " );
string param = HttpUtility.UrlEncode( " merId " , myEncoding) + " = " + HttpUtility.UrlEncode(merId, myEncoding)
+ " & " + HttpUtility.UrlEncode( " merDate " , myEncoding) + " = " + HttpUtility.UrlEncode(merDate, myEncoding)
+ " & " + HttpUtility.UrlEncode( " merSeqId " , myEncoding) + " = " + HttpUtility.UrlEncode(merSeqId, myEncoding)
+ " & " + HttpUtility.UrlEncode( " version " , myEncoding) + " = " + HttpUtility.UrlEncode(version, myEncoding)
+ " & " + HttpUtility.UrlEncode( " chkValue " , myEncoding) + " = " + HttpUtility.UrlEncode(sbValue.ToString(), myEncoding);
byte [] postBytes = Encoding.ASCII.GetBytes(param);
try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create( " 请求地址 " );
req.Method = " POST " ;
req.ContentType = " application/x-www-form-urlencoded;charset=GBK " ;
req.ContentLength = postBytes.Length;
Stream webStream = req.GetRequestStream(); // 发送数据
webStream.Write(postBytes, 0 , postBytes.Length);
webStream.Close();
// 获取返回数据
HttpWebResponse webResponse = (HttpWebResponse)req.GetResponse();
StreamReader reader = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding( " GBK " ));
sResult = reader.ReadToEnd();
sResult.Trim();
}
catch (Exception e)
{
sResult = "" ;
return sResult;
}