How do I make calls to a REST API using C#?

后端 未结 15 1860
面向向阳花
面向向阳花 2020-11-22 08:10

This is the code I have so far:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Net.Http;
usi         


        
15条回答
  •  广开言路
    2020-11-22 08:43

    GET:

    // GET JSON Response
    public WeatherResponseModel GET(string url) {
        WeatherResponseModel model = new WeatherResponseModel();
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        try {
            WebResponse response = request.GetResponse();
            using(Stream responseStream = response.GetResponseStream()) {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                model = JsonConvert.DeserializeObject < WeatherResponseModel > (reader.ReadToEnd());
            }
        } catch (WebException ex) {
            WebResponse errorResponse = ex.Response;
            using(Stream responseStream = errorResponse.GetResponseStream()) {
                StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                String errorText = reader.ReadToEnd();
                // Log errorText
            }
            throw;
        }
        return model;
    }
    

    POST:

    // POST a JSON string
    void POST(string url, string jsonContent) {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
    
        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        Byte[]byteArray = encoding.GetBytes(jsonContent);
    
        request.ContentLength = byteArray.Length;
        request.ContentType =  @ "application/json";
    
        using(Stream dataStream = request.GetRequestStream()) {
            dataStream.Write(byteArray, 0, byteArray.Length);
        }
    
        long length = 0;
        try {
            using(HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
                // Got response
                length = response.ContentLength;
            }
        } catch (WebException ex) {
            WebResponse errorResponse = ex.Response;
            using(Stream responseStream = errorResponse.GetResponseStream()) {
                StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                String errorText = reader.ReadToEnd();
                // Log errorText
            }
            throw;
        }
    }
    

    Note: To serialize and desirialze JSON, I used the Newtonsoft.Json NuGet package.

提交回复
热议问题