C# +webAPI+post+Httpclient

C# +webAPI+post+Httpclient

猿掌柜
2022-11-28 / 0 评论 / 12 阅读 / 正在检测是否收录...

net6已废弃WebRequest.Create
推荐使用httpclient

{mtitle}下面为GET方法{/mtitle}


            string path = "";
            System.IO.FileStream fs;
            HttpClient client = new HttpClient();//http对象
            var uri = new Uri(Uri.EscapeDataString(url));
            byte[] urlContents = await client.GetByteArrayAsync(uri);
            fs = new System.IO.FileStream(AppDomain.CurrentDomain.BaseDirectory + "1.jpg", 
           System.IO.FileMode.CreateNew);
            fs.Write(urlContents, 0, urlContents.Length);

一个下载图片的例子
使用方法
Downoload(imgSourceURL, "D:\\qqq.jpg");
返回bool true 即下载到上面的路径

private static bool Downoload(string uri,string fname)
        {
            var server = new Uri(uri);
            var p = Path.GetDirectoryName(fname);
            if (!Directory.Exists(p))
            {
                Directory.CreateDirectory(p);
            }
            var httpClient = new HttpClient();
            var responseMessage = httpClient.GetAsync(server).Result;
            if (responseMessage.IsSuccessStatusCode)
            {
                using (var fs = File.Create(fname))
                {
                    var streamFromService = responseMessage.Content.ReadAsStreamAsync().Result;
                    streamFromService.CopyTo(fs);
                    return true;
                }
            }
            else
            {
                return false;
            }
        }

{mtitle}下面为POS方法{/mtitle}
post使用
string result = HttpClientPost(warnurl, ddd);

            HttpClient httpClient = new HttpClient();//http对象
            //表头参数
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            
            //httpClient.DefaultRequestHeaders.Add("Authorization", "c2hpbmVlbmVyZ3k6U2hpbmVlbmVyZ3kxMjM0NTY3YQ==");
            HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post, url);

            httpRequest.Headers.TryAddWithoutValidation("Authorization", "xxxxx");
            //httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
            httpRequest.Method=HttpMethod.Post;
            httpRequest.Content = new StringContent(JsonConvert.SerializeObject(datajson), Encoding.UTF8, "application/x-www-form-urlencoded");
            //HttpResponseMessage result = await httpClient.SendAsync(httpRequest);
            //Console.WriteLine(result.ReasonPhrase);
            //转为链接需要的格式
            //HttpContent httpContent = new JsonContent(datajson);
            //请求
            HttpResponseMessage response = httpClient.SendAsync(httpRequest).Result;
            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                if (t != null)
                {
                    return t.Result;
                }
            }
            return "";
public class JsonContent : StringContent
        {
            public JsonContent(object obj) :
               base(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")
            
        }
1

评论 (0)

取消