zoukankan      html  css  js  c++  java
  • HttpClient

     private async Task sendGETRequest()
            {
                //连环using
                using (var handler = new HttpClientHandler()
                {
                    UseCookies = true,
                    UseDefaultCredentials = true,
                    CookieContainer = new CookieContainer()
                })
                using (var client = new HttpClient(handler))
                {
                    client.BaseAddress = new Uri(S.domain);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    handler.CookieContainer.Add(client.BaseAddress, new Cookie("keyOne", "ttc")); //add cookie
                    HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, "api/getSetCookieAndHeader"); 
                    requestMessage.Headers.Add("key", "value"); //add header
                    HttpResponseMessage response = await client.SendAsync(requestMessage);
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        string responseAsString = await response.Content.ReadAsStringAsync();
                    }               
                }
            }
            public async Task sendPOSTRequest()
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(S.domain);
                    var query = S.ParseQueryString("");
                    query["returnUrl"] = "gowhere";
                    string queryStr = query.toQueryString();
                    HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "Home/Login?" + queryStr);
                    requestMessage.Headers.Add("key", "value"); //add header  
                    //Content-Type 不可以加进去 header哦, 要json 或 FormUrlEncodedContent 就要像下面这样写    
                    //requestMessage.Content = new StringContent("{"name":"John Doe","age":33}", Encoding.UTF8, "application/json"); 
                    requestMessage.Content = new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair<string, string>("name", "nameValue")
                    });
                    HttpResponseMessage response = await client.SendAsync(requestMessage);
                    string responseAsString = await response.Content.ReadAsStringAsync(); 
                }
            }
  • 相关阅读:
    《民工》随笔
    最近繁忙,暂停更新
    UVA 839 Not so Mobile
    UVA 310 Lsystem
    UVA 10602 Editor Nottoobad
    UVA 10562 Undraw the Trees
    UVA 327 Evaluating Simple C Expressions
    UVA 10954 Add All
    UVA 270 Lining Up
    UVA 699 The Falling Leaves
  • 原文地址:https://www.cnblogs.com/keatkeat/p/6169497.html
Copyright © 2011-2022 走看看