http请求记录
Posted yxcn
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
以上是关于http请求记录的主要内容,如果未能解决你的问题,请参考以下文章