C# http常見的 Post請求方法體
一、帶data引數傳遞:
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urlApi + url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
//驗證伺服器證書回撥自動驗證 ****關鍵****
ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
dataStr = JsonConvert.SerializeObject(dic);//要傳送的資料轉json格式
byte[] data = Encoding.UTF8.GetBytes("data=" + dataStr);
req.ContentLength = data.Length;
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version10;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
resp.Cookies = cookie.GetCookies(resp.ResponseUri);
Stream myResponseStream = resp.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
result = myStreamReader.ReadToEnd(); //獲取響應內容
myStreamReader.Close();
myResponseStream.Close();
LogHelper.ApiSend("接收Api返回:" + result);
return result;
二、經常使用到的方法體:
/// <summary>
/// 返回JSon資料
/// </summary>
/// <param name="JSONData">要處理的JSON資料</param>
/// <returns>返回的JSON處理字串</returns>
public static string HttpPostPush(string JSONData)
{
string strResult = "";
try
{
System.Net.ServicePointManager.DefaultConnectionLimit = 50;
byte[] bytes = Encoding.UTF8.GetBytes(JSONData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SystemParameterConfig.Push_Url);
request.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
//request.ContentLength = bytes.Length;
request.ContentType = "text/xml;charset=UTF-8";
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version11;
Stream reqstream = request.GetRequestStream();
reqstream.Write(bytes, 0, bytes.Length);
//request.Timeout = 10000;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamReceive = response.GetResponseStream();
Encoding encoding = Encoding.UTF8;
StreamReader streamReader = new StreamReader(streamReceive, encoding);
strResult = streamReader.ReadToEnd();
streamReceive.Dispose();
streamReader.Dispose();
}
catch (Exception e)
{
LogHelper.Error(e.Message);
}
finally
{
}
return strResult;
}
三、上傳檔案資料
http://blog.csdn.net/xxj_jing/article/details/50221113
四、參考部落格:https://www.cnblogs.com/webenh/p/5775543.html