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(); 
                }
            }
  • 相关阅读:
    Java通过JNI调用C/C++
    Using HTML5 audio and video
    vmstat输出项解释
    uva 11237
    NN优化方法对照:梯度下降、随机梯度下降和批量梯度下降
    认识与学习bash
    系统崩溃,大圣归来
    连载《一个程序员的生命周期》-25.到工业现场学习业务知识引发的思考
    ZOJ问题(2010浙江大学研究生复试上机题目[找规律] hdoj 3788)
    UIView的几个枚举定义
  • 原文地址:https://www.cnblogs.com/keatkeat/p/6169497.html
Copyright © 2011-2022 走看看