HTTP调用/请求 地址

        /// <summary>
        /// 
        /// </summary>
        /// <param name="requestURI">请求地址</param>
        /// <param name="requestMethod">请求方式</param>
        /// <param name="json">json入参</param>
        /// <returns></returns>
public static string SendHttpRequest(string requestURI, string requestMethod, string json = "")
        {
            string ReqResult = string.Empty;
            try
            {
                //json格式请求数据
                string requestData = json;
                //拼接URL
                string serviceUrl = requestURI;//string.Format("{0}/{1}", requestURI, requestMethod);
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
                //post请求
                myRequest.Method = requestMethod;
                //utf-8编码
                byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(requestData);

                myRequest.ContentLength = buf.Length;
                myRequest.Timeout = 60000;
                //指定为json否则会出错
                myRequest.ContentType = "application/json";
                myRequest.MaximumAutomaticRedirections = 1;
                myRequest.AllowAutoRedirect = true;
                Stream newStream = myRequest.GetRequestStream();
                newStream.Write(buf, 0, buf.Length);
                newStream.Close();

                //获得接口返回值
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                ReqResult = reader.ReadToEnd();
                reader.Close();
                myResponse.Close();
                return ReqResult;
            }
            catch (Exception ex)
            {
                return ReqResult = ex.Message.ToString();
            }
            
            
        }

以上则是基本HTTP请求---Json入参格式


HTTP基本请求---zip文件入参(hander 账号密码加密处理)

        /// <summary>
        /// Post-上传文件  上传请求zip格式文件
        /// </summary>
        /// <param name="url">上传请求地址</param>
        /// <param name="postData">文件地址</param>
        /// <returns></returns>
        public static string PostResponse(string url, string postData, out string statusCode)
        {
            string result = string.Empty;
            HttpResponseMessage response2 = new HttpResponseMessage();
            //设置Http的正文
            HttpContent httpContent = new StringContent(postData);
            //根据form表单 上传格式设置对应参数
            var content = new MultipartFormDataContent();
            if (postData.Contains("QyTest"))
            {
                content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(postData)), "dataFile", "QyTest.zip");
            }
            else
            {
                content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(postData)), "dataFile", "RyTest02.zip");
            }
            string str = "******";//hander 登录账号
            content.Add(new ByteArrayContent(System.Text.Encoding.UTF8.GetBytes(str)), "unitCode");
            str = "********";//hander 登录密码
            content.Add(new ByteArrayContent(System.Text.Encoding.UTF8.GetBytes(str)), "password");
            //设置Http的内容标头
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data");
            //设置Http的内容标头的字符
            httpContent.Headers.ContentType.CharSet = "utf-8";

            using (HttpClient httpClient = new HttpClient())
            {
                string value = "unitCode=00000:password=000000";//请求头 账号密码,与上方hander一致,根据业务需求来决定编写在哪
                httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.Default.GetBytes(value)));//转换basic 加密拼接
                httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");
                //异步发送Post请求
                try
                {
                    response2 = httpClient.PostAsync(url, content).Result;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                //Http响应状态码
                statusCode = response2.StatusCode.ToString();
                //确保Http响应成功
                if (response2.IsSuccessStatusCode)
                {
                    //异步读取返回信息
                    result = response2.Content.ReadAsStringAsync().Result;
                }
            }
            return result;
        }

POST请求,请求数据格式: x-www-form-urlencoded

        /// <summary>
        /// 
        /// </summary>
        /// <param name="requestURI">请求地址</param>
        /// <param name="requestMethod">post/get</param>
        /// <param name="json">请求数据</param>
        /// <returns></returns>
        public static string SendHttpRequest(string requestURI, string requestMethod, string json = "")
        {
            //json格式请求数据
            string requestData = json;
            //拼接URL
            string serviceUrl = requestURI;//string.Format("{0}/{1}", requestURI, requestMethod);
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            //post请求
            myRequest.Method = requestMethod;
            //utf-8编码
            byte[] buf = System.Text.Encoding.Default.GetBytes(requestData);

            myRequest.ContentLength = buf.Length;
            myRequest.Timeout = 50000;
            //指定为json否则会出错
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.MaximumAutomaticRedirections = 1;
            myRequest.AllowAutoRedirect = true;
            Stream newStream = myRequest.GetRequestStream();
            newStream.Write(buf, 0, buf.Length);
            newStream.Close();

            //获得接口返回值
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            string ReqResult = reader.ReadToEnd();
            reader.Close();
            myResponse.Close();
            return ReqResult;
        }

x-www-form-urlencoded 及是 Url数据格式,以下本人封装了一个Model转Url数据方法

        /// <summary>
        /// x-www-form-urlencoded请求参数拼接
        /// </summary>
        /// <param name="source">model</param>
        /// <returns>Url数据</returns>
        public static string ToUrlPaeameter(object source)
        {
            var buff = new StringBuilder(string.Empty);
            if (source == null) throw new ArgumentNullException("source", "入参为空");
            foreach (System.ComponentModel.PropertyDescriptor property in         System.ComponentModel.TypeDescriptor.GetProperties(source))
            {
                object value = property.GetValue(source);
                if (value != null)
                {
                    buff.Append(WebUtility.UrlEncode(property.Name) + "=" + WebUtility.UrlEncode(value + "") + "&");
                }
            }
            return buff.ToString().Trim('&');
        }

  • 14
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值