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(); 
                }
            }
  • 相关阅读:
    UI系统的分类
    DSL的概念
    什么是“图灵完备”?
    UI系统的作用
    redis——持久化方式RDB与AOF分析
    Redis能做什么?不能做什么?
    PHP Ajax 跨域问题最佳解决方案
    charles和Fiddler感觉哪个更好用
    Fiddler工具使用介绍一
    Xshell出现要继续使用此程序必须应用到最新的更新或使用新版本
  • 原文地址:https://www.cnblogs.com/keatkeat/p/6169497.html
Copyright © 2011-2022 走看看