.net 发起http请求例子和注意事项

 

#region----发起apiUrl请求----
        /// <summary>
        /// 发起apiUrl请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="paramData"></param>
        /// <param name="headerDic"></param>
        /// <returns></returns>
        public static string HttpPost(string url, string paramData, Dictionary<string, string> headerDic = null)
        {
            string result = string.Empty;
            try
            {
                string urlGet = url + "?" + paramData;
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(urlGet);
                wbRequest.ContentType = "application/x-www-form-urlencoded";
                wbRequest.KeepAlive = false;
                wbRequest.ProtocolVersion = HttpVersion.Version10;

                /*
                wbRequest.Method = "Post";
                wbRequest.ContentType = "application/x-www-form-urlencoded";
                wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);
                wbRequest.KeepAlive = false;
                wbRequest.ProtocolVersion = HttpVersion.Version10;

                if (headerDic != null && headerDic.Count > 0)
                {
                    foreach (var item in headerDic)
                    {
                        wbRequest.Headers.Add(item.Key, item.Value);
                    }
                }
                using (Stream requestStream = wbRequest.GetRequestStream())
                {
                    using (StreamWriter swrite = new StreamWriter(requestStream))
                    {
                        swrite.Write(paramData);
                    }
                }
                */

                /*
                                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
                                wbRequest.Method = "Post";
                                wbRequest.ContentType = "application/x-www-form-urlencoded";
                                wbRequest.KeepAlive = false;
                                wbRequest.ProtocolVersion = HttpVersion.Version10;
                                byte[] requestData = Encoding.UTF8.GetBytes(paramData);
                                wbRequest.ContentLength = requestData.Length;
                                Stream requestStream = wbRequest.GetRequestStream();
                                requestStream.Write(requestData, 0, requestData.Length);
                                requestStream.Close();
                                 */


                //接收返回包
                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    using (StreamReader sread = new StreamReader(responseStream))
                    {
                        result = sread.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                //记录日志
                //Console.WriteLine(ex.Message);
                throw ex;
            }

            return result;
        }
        #endregion

 

================================================================

#region----接收银行服务器发送回来的流----
        /// <summary>
        /// 接收银行服务器发送回来的流
        /// </summary>
        /// <returns></returns>
        public string GetPost()
        {
            try
            {
                System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;//接收微信端发送过来的xml
                int count = 0;
                byte[] buffer = new byte[s.Length];
                StringBuilder builder = new StringBuilder();
                while ((count = s.Read(buffer, 0, buffer.Length)) > 0)
                {
                    builder.Append(System.Web.HttpContext.Current.Request.ContentEncoding.GetString(buffer, 0, count));
                }
                s.Flush();
                s.Close();
                s.Dispose();
                return builder.ToString();
            }
            catch (Exception ex)
            {
                LogHelper.RecordErro("[GetPost]银行支付,接收银行服务器发送回来的流报错", ex);
                return null;
            }
        }
        #endregion

---------------------------------------------------------------------------

//接收返回包
            string getJson = GetPost();

--------------------------------------------------------------------------

================================================================

 

远程服务器返回错误:(415Unsupported Media Type.

原因:头部信息ContentType不符合要求,可能是 application/x-www-form-urlencoded  ,也可能是 application/json ,根据实际服务器能够接受的信息类型为准。

 

 

远程服务器返回错误:(400)错误的请求。

原因:ContentType写了application/json      ,提交的数据就不能是From格式,必须是Json格式。

 

================================================================

提交Json参数请求远程接口

 

Dictionary<string, string> paramsDir = new Dictionary<string, string>();
            paramsDir.Add("accountId", accountId);
            paramsDir.Add("payType", payType);
            paramsDir.Add("orderId", orderId);
            paramsDir.Add("commodity", commodit);
            paramsDir.Add("amount", amount);
            paramsDir.Add("responseUrl", responseUrl);
            paramsDir.Add("ext", ext);
            paramsDir.Add("mac", mac);
            paramsDir.Add("versionParam", versionParam);
            paramsDir.Add("limitPay", limitPay);

            string postJsonLog = JsonConvert.SerializeObject(paramsDir);
            LogHelper.Info(currentMethodLog + "请求的数据:" + postJsonLog);
            string resultHttpJson = HttpUtils.PostJson(url, paramsDir, null);

-------------------------------------------------------------------------

 

#region----提交Json参数请求远程接口----
        /// <summary>
        /// 提交Json参数请求远程接口
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <param name="charset"></param>
        /// <returns></returns>
        public static string PostJson(string url, IDictionary<string, string> parameters, Encoding charset = null)
        {
            HttpWebRequest request = null;
            //HTTPSQ请求              
            request = WebRequest.Create(url) as HttpWebRequest;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Method = "POST";
            request.ContentType = "application/json";
            //如果需要POST数据     
            if (!(parameters == null || parameters.Count == 0))
            {
//提交的Json格式的参数数据
                string buffer = JsonConvert.SerializeObject(parameters);
                charset = (charset == null ? Encoding.GetEncoding("utf-8") : charset);
                byte[] data = charset.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            var webResponse = request.GetResponse() as HttpWebResponse;
            using (var steam = webResponse.GetResponseStream())
            {
                StreamReader sr = new StreamReader(steam);
                return sr.ReadToEnd();
            }
        }
        #endregion

 

 

提交Form参数请求远程接口

 

 

#region----提交Form参数请求远程接口----
        /// <summary>
        /// 提交Form参数请求远程接口;
        /// 仅限参数为formBody的请求;
        /// </summary>
        /// <param name="url">接口uri</param>
        /// <param name="parameters">参数</param>
        /// <param name="charset">编码</param>
        /// <returns></returns>
        public static string PostForm(string url, IDictionary<string, string> parameters, Encoding charset = null)
        {
            HttpWebRequest request = null;
            //HTTPSQ请求  
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            request = WebRequest.Create(url) as HttpWebRequest;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = DefaultUserAgent;
            //request.Headers.Add("X-Forwarded-For", ip);
            //request.Headers.Add("HTTP_X_FORWARDED_FOR", ip);
            //request.Headers.Add("HTTP_CLIENT_IP", ip);
            //request.Headers.Add("REMOTE_ADDR", ip);
            ////request.Headers.Add("Host", "http://www.gd.xinhuanet.com/zt18/gdppbj/wap.html");
            //如果需要POST数据     
            if (!(parameters == null || parameters.Count == 0))
            {
//提交的Form格式的参数数据
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
                charset = (charset == null ? Encoding.GetEncoding("utf-8") : charset);
                byte[] data = charset.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            var webResponse = request.GetResponse() as HttpWebResponse;

            using (var steam = webResponse.GetResponseStream())
            {
                StreamReader sr = new StreamReader(steam);
                return sr.ReadToEnd();
            }
        }
        #endregion

 

==============================================================

接口接收Form表单,查看传了什么参数过来

LogHelper.Info(currentMethodLog + "记录接收的每个参数名字:" + HttpContext.Request.Form.AllKeys.ToJson());

 

posted on 2022-09-20 16:38  Jankie1122  阅读(163)  评论(0编辑  收藏  举报