{"id":6510,"date":"2024-03-20T10:01:01","date_gmt":"2024-03-20T02:01:01","guid":{"rendered":""},"modified":"2024-03-20T10:01:01","modified_gmt":"2024-03-20T02:01:01","slug":"\u4f7f\u7528C# \u53d1\u9001\u4e0d\u540c\u4fe1\u606f\u683c\u5f0f\u7684http\u8bf7\u6c42","status":"publish","type":"post","link":"https:\/\/mushiming.com\/6510.html","title":{"rendered":"\u4f7f\u7528C# \u53d1\u9001\u4e0d\u540c\u4fe1\u606f\u683c\u5f0f\u7684http\u8bf7\u6c42"},"content":{"rendered":"
1.\u6700\u5e38\u89c1\u7684post json<\/p>\n
var jsonObject = JsonConvert.SerializeObject(model);\n...\n var str = new StringContent(jsonObject, Encoding.UTF8, \"application\/json\");\n...<\/code><\/pre>\n 2. url encoded content\u683c\u5f0f<\/p>\n
...\n var formContent = new FormUrlEncodedContent(new[]\n {\n new KeyValuePair<string, string>(\"k1\", \"v1\"),\n new KeyValuePair<string, string>(\"k2\", \"v2\")\n });\n\n var request = new HttpRequestMessage\n {\n Content = formContent,\n Method = HttpMethod.Post,\n RequestUri = new Uri(url)\n };\n var ret = httpClient.SendAsync(request).Result;<\/code><\/pre>\n\u4e5f\u53ef\u4ee5\u4f7f\u7528\u4ee5\u4e0b\u8f85\u52a9\u51fd\u6570\u6765\u5b8c\u6210<\/p>\n
private static TRes ApiCallAsFormData<TRes>(string url, IEnumerable<KeyValuePair<string, string>> data)\n {\n try\n {\n using (var httpClient = new HttpClient())\n {\n var formContent = new FormUrlEncodedContent(data);\n\n var ret = httpClient.PostAsync(url, formContent).Result;\n var jsonRet = ret.Content.ReadAsStringAsync().Result;\n return JsonConvert.DeserializeObject<TRes>(jsonRet);\n }\n }\n catch (Exception ex)\n {\n _log.Error(ex);\n return default(TRes);\n }\n }\n...<\/code><\/pre>\n3. \u53d1\u9001\u5176\u4ed6 http \u8bf7\u6c42\u7c7b\u578b (PUT,DELETE,PATCH)<\/p>\n
...\n var request = new HttpRequestMessage\n {\n Method = HttpMethod.Delete,\n RequestUri = new Uri($\"url\")\n };\nvar ret = httpClient.SendAsync(request).Result;\n...<\/code><\/pre>\n3.post\u6587\u4ef6\uff0cmultiplart\u7c7b\u578b
\u53ef\u4f7f\u7528\u4ee5\u4e0bhelper\u7c7b\u5b8c\u6210(\u53ef\u4f20\u9012oauth token\u6216cookie\uff09<\/p>\n
public class FormUploadHelper\n {\n private static readonly Encoding encoding = Encoding.UTF8;\n\n\n public static HttpWebResponse MultipartFormDataPost(string postUrl,\n string userAgent,\n Dictionary<string, object> postParameters, string token, IList<Cookie> cookies = null)\n {\n string formDataBoundary = String.Format(\"----------{0:N}\", Guid.NewGuid());\n string contentType = \"multipart\/form-data; boundary=\" + formDataBoundary;\n\n byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);\n\n return PostForm(postUrl, userAgent, contentType, formData, token, cookies);\n }\n\n private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType,\n byte[] formData, string token, IList<Cookie> cookies)\n {\n HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;\n\n if (request == null)\n {\n throw new NullReferenceException(\"request is not a http request\");\n }\n\n \/\/ Set up the request properties.\n request.Method = \"POST\";\n request.ContentType = contentType;\n if (!string.IsNullOrEmpty(token))\n {\n request.Headers.Add(\"accessToken\", token);\n }\n\n if (cookies != null && cookies.Count > 0)\n {\n if (request.CookieContainer == null)\n {\n request.CookieContainer = new CookieContainer();\n }\n foreach (var cookie in cookies)\n {\n request.CookieContainer.Add(cookie);\n }\n }\n else\n {\n request.CookieContainer = new CookieContainer();\n }\n\n request.UserAgent = userAgent;\n \n request.ContentLength = formData.Length;\n\n \/\/ You could add authentication here as well if needed:\n \/\/ request.PreAuthenticate = true;\n \/\/ request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;\n \/\/ request.Headers.Add(\"Authorization\", \"Basic \" + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(\"username\" + \":\" + \"password\")));\n\n \/\/ Send the form data to the request.\n using (Stream requestStream = request.GetRequestStream())\n {\n requestStream.Write(formData, 0, formData.Length);\n requestStream.Close();\n }\n\n return request.GetResponse() as HttpWebResponse;\n }\n\n private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)\n {\n Stream formDataStream = new System.IO.MemoryStream();\n bool needsCLRF = false;\n\n if (postParameters != null)\n {\n foreach (var param in postParameters)\n {\n \/\/ Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.\n \/\/ Skip it on the first parameter, add it to subsequent parameters.\n if (needsCLRF)\n formDataStream.Write(encoding.GetBytes(\"\\r\\n\"), 0, encoding.GetByteCount(\"\\r\\n\"));\n\n needsCLRF = true;\n\n if (param.Value is FileParameter)\n {\n FileParameter fileToUpload = (FileParameter)param.Value;\n\n \/\/ Add just the first part of this param, since we will write the file data directly to the Stream\n string header = string.Format(\n \"--{0}\\r\\nContent-Disposition: form-data; name=\\\"{1}\\\"; filename=\\\"{2}\\\"\\r\\nContent-Type: {3}\\r\\n\\r\\n\",\n boundary,\n param.Key,\n fileToUpload.FileName ?? param.Key,\n fileToUpload.ContentType ?? \"application\/octet-stream\");\n\n formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));\n\n \/\/ Write the file data directly to the Stream, rather than serializing it to a string.\n formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);\n }\n else\n {\n string postData = string.Format(\n \"--{0}\\r\\nContent-Disposition: form-data; name=\\\"{1}\\\"\\r\\n\\r\\n{2}\",\n boundary,\n param.Key,\n param.Value);\n formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));\n }\n }\n }\n\n \/\/ Add the end of the request. Start with a newline\n string footer = \"\\r\\n--\" + boundary + \"--\\r\\n\";\n formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));\n\n \/\/ Dump the Stream into a byte[]\n formDataStream.Position = 0;\n byte[] formData = new byte[formDataStream.Length];\n formDataStream.Read(formData, 0, formData.Length);\n formDataStream.Close();\n\n return formData;\n }\n }<\/code><\/pre>\n4.\u8bf7\u6c42\u4e2d\u643a\u5e26cookie
\u83b7\u53d6cookie<\/p>\n
using (var handler = new HttpClientHandler())\n {\n using (var httpClient = new HttpClient(handler))\n {\n...\n CookieContainer cookies = new CookieContainer();\n handler.CookieContainer = cookies;\n...\n HttpResponseMessage authenticationResponse = httpClient.PostAsync(uri, str).Result;\n var sessionCookie = cookies.GetCookies(uri).Cast<Cookie>().ToList();\n...\n}\n}<\/code><\/pre>\n\u53d1\u9001cookie
<\/p>\n
using (var handler = new HttpClientHandler())\n {\n using (var httpClient = new HttpClient(handler))\n {\n...\n...\n foreach (var cookie in __sessionCookie)\n {\n handler.CookieContainer.Add(cookie);\n }\n...<\/code><\/pre>\n 5. http \u957f\u8fde\u63a5\u5f02\u6b65\u9010\u884c\u89e3\u6790<\/p>\n
using (HttpWebResponse webResponse = req.GetResponse(uri))\n using (Stream responseStream = webResponse.GetResponseStream())\n {\n if (responseStream != null)\n {\n using (StreamReader streamReader = new StreamReader(responseStream))\n {\n while (!streamReader.EndOfStream)\n {\n response = await streamReader.ReadLineAsync();\n ...\n }\n }\n }\n }\n <\/code><\/pre>\n <\/p>\n","protected":false},"excerpt":{"rendered":"\u4f7f\u7528C# \u53d1\u9001\u4e0d\u540c\u4fe1\u606f\u683c\u5f0f\u7684http\u8bf7\u6c421.\u6700\u5e38\u89c1\u7684postjsonvarjsonObject=JsonConvert.SerializeObject(model);...varstr=newStri...","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[],"_links":{"self":[{"href":"https:\/\/mushiming.com\/wp-json\/wp\/v2\/posts\/6510"}],"collection":[{"href":"https:\/\/mushiming.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mushiming.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mushiming.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mushiming.com\/wp-json\/wp\/v2\/comments?post=6510"}],"version-history":[{"count":0,"href":"https:\/\/mushiming.com\/wp-json\/wp\/v2\/posts\/6510\/revisions"}],"wp:attachment":[{"href":"https:\/\/mushiming.com\/wp-json\/wp\/v2\/media?parent=6510"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mushiming.com\/wp-json\/wp\/v2\/categories?post=6510"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mushiming.com\/wp-json\/wp\/v2\/tags?post=6510"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}