c# HttpClient,WebClient常用请求
get
WebClient webClient = new WebClient(); ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072; //ServicePointManager.Expect100Continue = true; //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; webClient.Credentials = CredentialCache.DefaultCredentials; Byte[] pageData = webClient.DownloadData(url); webClient.Dispose(); string jsondata = System.Text.Encoding.UTF8.GetString(pageData); return (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(jsondata);
post +User-Agent +Authorization
public static string PostJson(string url,string json, string token) { using (var client = new HttpClient()) { //client.DefaultRequestHeaders.Add("Authorization", "Bearer "+token+""); //var data = new StringContent(json, Encoding.UTF8, "application/json"); //var response = client.PostAsync(url, data).GetAwaiter().GetResult(); //string result = response.Content.ReadAsStringAsync().Result; //return result; client.DefaultRequestHeaders.Add("User-Agent", "Apifox/1.0.0 (https://apifox.com)"); var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); var response = client.SendAsync(request).GetAwaiter().GetResult(); string result = response.Content.ReadAsStringAsync().Result; return result; } }
post + form-data
static async Task Main(string[] args) { using (var client = new HttpClient()) { var formData = new MultipartFormDataContent(); formData.Add(new StringContent("John Doe"), "name"); formData.Add(new StringContent("johndoe@example.com"), "email"); var response = await client.PostAsync("http://example.com/submit-form", formData); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } }
我们使用formData.Add
方法来添加表单数据,其中第一个参数是表单项的内容,第二个参数是表单项的名称
原文地址:https://blog.csdn.net/qtvb1987/article/details/143700625
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!