C#中http请求

C#中HTTP请求失败及问题处理方案记录

  1. 先上一段代码
 string responseString = string.Empty;

            ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;// 4.0环境下https请求设置,否则会报请求被中止: 未能创建 SSL/TLS 安全通道。   
            //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tlsl;环境4.5以上的写法
            
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = "Post";

            request.ContentType = "application/x-www-form-urlencoded";//;charset=UTF-8;

            request.Accept = "*/*";

            request.Timeout = 60 * 1000 * 5;

            request.Headers.Add("Accept-Encoding", "identity");//强行要求服务器不压缩,  当你请求发现返回的数据长度response.ContentLength = -1,这会就要注意可能是服务器对下发的数据进行了压缩,如果你不设置会收到一串乱码或进行数据解压缩。
            //dic["app_key"] = HttpUtility.UrlEncode(app_key); 这里设置可以避免输入的参数里面有转义符导致参数错误。如果请求一直报错可以检查自己的参数并进行这样的设置

            string paramsData = ParseToString(dic);

            byte[] buffer = Encoding.UTF8.GetBytes(paramsData);
            //byte[] buffer = HttpUtility.UrlEncodeUnicodeToBytes(paramsData);// Encoding.UTF8.GetBytes(paramsData);

            request.ContentLength = buffer.Length;

            using (Stream writer = request.GetRequestStream())
            {
                writer.Write(buffer, 0, buffer.Length);
            }
            AsyncCallback callback = new AsyncCallback(state =>
            {
                var asyncrequest = state.AsyncState as HttpWebRequest;

                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(state);

                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    responseString = reader.ReadToEnd();
                }
            });

            IAsyncResult result = request.BeginGetResponse(callback, request);

            return responseString;
  1. ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;// 4.0环境下https请求设置,否则会报请求被中止: 未能创建 SSL/TLS 安全通道。
  2. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;环境4.5以上的写法
  3. request.Headers.Add(“Accept-Encoding”, “identity”);//强行要求服务器不压缩, 当你请求发现返回的数据长度response.ContentLength = -1,这会就要注意可能是服务器对下发的数据进行了压缩,如果你不设置会收到一串乱码或进行数据解压缩。
  4. HttpUtility.UrlEncode(app_key); 特别的说明这个是因为我请求别人的接口一直返回密钥错误,但是我密钥是正确的,但是我发现密钥中有个斜杠。用POSTMAN请求就是正确返回的,我直接请求就报错误。后面才这样设置后才能正确返回。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值