C\#WebApi 호출 실현

4445 단어 C#호출WebApi
1.WebRequest 방식
Post:

private void button1_Click(object sender, EventArgs e)
        {
           string ss= HttpPost("http://localhost:41558/api/Demo/PostXXX", "{Code:\"test089\",Name:\"test1\"}");
        }

        public static string HttpPost(string url, string body)
        {
            //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";
       
            byte[] buffer = encoding.GetBytes(body);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }

Get:

private void button1_Click(object sender, EventArgs e)
        {
            string ss = HttpGet("http://localhost:41558/api/Demo/GetXXX?Name=  ");
        }

        public static string HttpGet(string url)
        {
            //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";
           
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
2.HttpClient 방식
Post:

private async void button2_Click(object sender, EventArgs e)
{
     HttpClient client = new HttpClient();
     // HttpClient  Delete Method
     HttpResponseMessage response = await client.DeleteAsync("http://localhost:41558/api/Demo"+"/1");
     if (response.IsSuccessStatusCode)
         MessageBox.Show("  ");
}

private async void button3_Click(object sender, EventArgs e)
{
     //          DataContractJsonSerializer
     DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(People));
     MemoryStream ms = new MemoryStream();
     //     MemoryStream
     serializer.WriteObject(ms, new People() { Id = 1, Name = "Hello ni" });
     //       Position
     ms.Position = 0;
     HttpContent content = new StreamContent(ms);// MemoryStream  HttpContent
     content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
     HttpClient client = new HttpClient();
     // HttpClient  Put Method
     HttpResponseMessage response = await client.PutAsync("http://localhost:41558/api/Demo"+ "/1", content);
     if (response.IsSuccessStatusCode)
         MessageBox.Show("  ");
}
Get:

using (WebClient client = new WebClient())
{
     client.Headers["Type"] = "GET";
     client.Headers["Accept"] = "application/json";
     client.Encoding = Encoding.UTF8;
     client.DownloadStringCompleted += (senderobj, es) =>
     {
         var obj = es.Result;
     };
     client.DownloadStringAsync("http://localhost:41558/api/Demo");
}
C\#WebApi 호출 실현 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 관련 C\#WebApi 내용 을 사용 하려 면 예전 의 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많은 응원 부 탁 드 리 겠 습 니 다!

좋은 웹페이지 즐겨찾기