C#請求API,沒有token

//API的url

string url = "";

// 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(url);

            // 设置请求方式为POST
            myRequest.Method = "POST";

            // 设置请求内容类型为JSON
            myRequest.ContentType = "application/json";

            // 设置请求内容长度
            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);

Result類:可以自定義

public class Result
{
    public string ReturnCode { get; set; }
    public string ReturnMessage { get; set; }
}

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值