try
{
//API的url
string API_Url = "";
string token = "";
// Json传参,根據API的傳入參數賦值
object json = new object();
json = new
{
parm_1= "",
parm_2= ""
};
//json對象轉成字符串
string strjson = JsonConvert.SerializeObject(json);
// 将string转换为UTF8编码的字节数组byte[]
byte[] data = Encoding.UTF8.GetBytes(strjson);
#region 解決報錯: 無法建立 SSL/TLS 的安全通道。
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
// 如果你的程序是.NET 4.0的,可以这样写:
//ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
#endregion
// 创建HttpWebRequest对象
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(API_Url);
// 设置请求方式为POST
myRequest.Method = "POST";
// 设置请求内容类型为JSON
myRequest.ContentType = "application/json";
//給請求頭添加token,格式:Bearer+空格+token,空格用於服務器解析數據
myRequest.Headers.Add("Authorization", "Bearer " + token);
// 设置请求内容长度
myRequest.ContentLength = data.Length;
// myRequest.Timeout = 2000;
// 获取请求流并写入请求内容
using (Stream wStream = myRequest.GetRequestStream())
{
wStream.Write(data, 0, data.Length);
}
// 获取响应对象
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
// 读取响应流
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
//string hh = reader.ReadToEnd();
//解码响应内容
string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());
//反转义响应内容,處理中文
string res = Regex.Unescape(returnXml);
//把json格式的字符串轉爲類對象
Result result = JsonConvert.DeserializeObject<Result>(res);
return result;
}
catch (Exception ex)
{
throw ex;
}
Result類:可以自定義
public class Result
{
public string ReturnCode { get; set; }
public string ReturnMessage { get; set; }
}