c#发送http请求注意

时间:2021-08-20 12:16:16

这里要注意几个点:
第一就是编码,如果编码不对,容易中文乱码
第二就是ContentType 如果设置不对,有可能连方法都调试不进去(我api用的是MVC的普通controller)
第三就是paramData参数形式要与ContentType保持一致

        /// <summary>
/// 发送POST请求
/// </summary>
/// <param name="postUrl">api</param>
/// <param name="paramData">参数,一般是param1=1&m2=2这种形式</param>
/// <param name="dataEncode">编码</param>
/// <returns></returns>
private string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
{
string ret = string.Empty;
try
{
byte[] byteArray = dataEncode.GetBytes(paramData); //转化
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
//webReq.ContentType = "application/json";
webReq.ContentLength = byteArray.Length;
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, , byteArray.Length);//写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
ret = sr.ReadToEnd();
sr.Close();
response.Close();
newStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return ret;
}