• http请求记录


    对接一个第三方接口请求封装记录,但是使用Tests<T>(),Post<T>()方法都失败了,HttpPost()方法成功

    前提:form-data 参数格式,

           #region  application类型请求
            public T Test<T>(string url, object form)
            {
                T result = default(T);
                var watch = Stopwatch.StartNew();
                try
                {
                    //string requestString = JsonConvert.SerializeObject(form);
                    string requestString = string.Empty;
                    foreach (var property in form.GetType().GetProperties())
                    {
                        requestString = requestString + property.Name.ToLower() + "=" + property.GetValue(form).ToString() + "&";
                        //dict.Add(property.Name.ToLower(), property.GetValue(form).ToString());
                    }
                    requestString = requestString.TrimEnd('&');
    
    
                    using (var client = new System.Net.Http.HttpClient())
                    {
                        //var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(dict) };
                        var request = HttpWebRequest.Create(url);
                        request.Method = "POST";
                        request.ContentType = "application/x-www-form-urlencoded";
                        byte[] data = Encoding.UTF8.GetBytes(requestString);
                        request.ContentLength = data.Length;
                        Stream newStream = request.GetRequestStream();
                        // Send the data.
                        newStream.Write(data, 0, data.Length);
                        var temp = request.GetResponse();
                        HttpWebResponse myResponse = (HttpWebResponse)request.GetResponse();
                        StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                        string content = reader.ReadToEnd();
                        Console.WriteLine(content);
                        Console.ReadLine();
                    }
                }
                catch (Exception ex)
                {
                    string temp = ex.Message;
                }
                return result;
            }
            #endregion
    
            #region multipart类型请求
            /// <summary>
            /// 把对象类型参数转为Dictionary<string, string> 类型
            /// </summary>
            /// <param name="form"></param>
            /// <returns></returns>
            private Dictionary<string, string> GetContentDictionary(object form)
            {
                var dict = new Dictionary<string, string>();
                foreach (var property in form.GetType().GetProperties())
                {
                    dict.Add(property.Name.ToLower(), property.GetValue(form).ToString());
                }
                return dict;
            }
            public T Post<T>(object request, string url)
            { 
                var dic = GetContentDictionary(request);
                var result = PostMutipart<T>(url, dic);
                return default(T);
            }
            public T PostMutipart<T>(string requestUri, Dictionary<string, string> keyValue)
            {
                HttpClientHandler handler = new HttpClientHandler();
                handler.UseProxy = false;
                handler.UseCookies = false;
                System.Net.Http.HttpClient _httpClient = new System.Net.Http.HttpClient(handler) { Timeout = TimeSpan.FromSeconds(60) };
                var watch = Stopwatch.StartNew();
                T result = default(T);
                var statusCode = HttpStatusCode.OK;
                try
                {
    
                    string responseBody = null;
                    using (var multipartFormDataContent = new MultipartFormDataContent())
                    {
                        foreach (var keyValuePair in keyValue)
                        {
                            multipartFormDataContent.Add(new StringContent(keyValuePair.Value),
                                String.Format(""{0}"", keyValuePair.Key));
                        }
                        var response = _httpClient.PostAsync(requestUri, multipartFormDataContent).GetAwaiter().GetResult();
                        responseBody = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                        statusCode = response.StatusCode;
                        if (responseBody != null && responseBody.Length > 0)
                        {
                            result = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responseBody);
                        }
                    }
                }
                catch (Exception ex)
                {
                    result = default(T);
                }
                return result;
            }
            #endregion
    
            #region WebRequest 请求
            public string HttpPost(string url, string postData)
            {
                string result = string.Empty;
                try
                {
                    var data = Encoding.UTF8.GetBytes(postData);
                    WebRequest res = WebRequest.Create(url);
                    res.ContentType = "application/x-www-form-urlencoded";
                    res.Method = "post";
                    res.UseDefaultCredentials = true;
                    res.ContentLength = data.Length;
                    var task = res.GetResponseAsync();
                    using (var stream = res.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
    
                    WebResponse rep = task.Result;
                    Stream respStream = rep.GetResponseStream();
                    using (StreamReader reader = new StreamReader(respStream, Encoding.Default))
                    {
                        result = reader.ReadToEnd();
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.ToString());
                }
    
                return result;
            }
            #endregion

     补充Post方法的参数类型

            public TokenReponse getToken(TokenRequest request)
            {
                string requestString = string.Empty;
                foreach (var property in request.GetType().GetProperties())
                {
                    requestString = requestString + property.Name.ToLower() + "=" + property.GetValue(request).ToString() + "&";
                    //dict.Add(property.Name.ToLower(), property.GetValue(form).ToString());
                }
                requestString = requestString.TrimEnd('&');
                var response = HttpPost(url, requestString);
                return null;
            }
  • 相关阅读:
    刷新界面
    分页加载数据(每次10条内容)的简单计算
    Intent传输包含对象的List集合
    android定时更新文件
    java中byte数据转换为c#的byte数据
    java zip文件的解压缩(支持中文文件名)
    Redis PHP扩展安装步骤
    CentOS6.5 开机启动自动运行redis服务
    centos7.2挂载硬盘攻略
    探究:Adobe Premiere Pro CC 2018 导入SRT字幕显示不全问题
  • 原文地址:https://www.cnblogs.com/yxcn/p/11090510.html
Copyright © 2020-2023  润新知