1. 程式人生 > 實用技巧 >後端請求介面的幾種方式

後端請求介面的幾種方式

//方法A:HttpClient(首選)
  using System.Net.Http;
       
     private static readonly HttpClient client = new HttpClient();
     //POST
       ar values = new Dictionary<string, string>
    {
        { "thing1", "hello" },
        { "thing2", "world" }
    };

    var content = new FormUrlEncodedContent(values);

    
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content); var responseString = await response.Content.ReadAsStringAsync(); //GET var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx"); //方法B:第三方庫 //RestSharp //POST var client = new
RestClient("http://example.com"); // client.Authenticator = new HttpBasicAuthenticator(username, password); var request = new RestRequest("resource/{id}"); request.AddParameter("thing1", "Hello"); request.AddParameter("thing2", "world"); request.AddHeader("header", "value"); request.AddFile(
"file", path); var response = client.Post(request); var content = response.Content; // Raw content as string var response2 = client.Post<Person>(request); var name = response2.Data.Name; //Flurl.Http using Flurl.Http; //POST var responseString = await "http://www.example.com/recepticle.aspx" .PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" }) .ReceiveString(); //GET var responseString = await "http://www.example.com/recepticle.aspx" .GetStringAsync(); //方法C:HttpWebRequest using System.Net; using System.Text; // For class Encoding using System.IO; // For StreamReader //POST var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx"); var postData = "thing1=" + Uri.EscapeDataString("hello"); postData += "&thing2=" + Uri.EscapeDataString("world"); var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); //GET var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx"); var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); //方法D:WebClient using System.Net; using System.Collections.Specialized; //POST using (var client = new WebClient()) { var values = new NameValueCollection(); values["thing1"] = "hello"; values["thing2"] = "world"; var response = client.UploadValues("http://www.example.com/recepticle.aspx", values); var responseString = Encoding.Default.GetString(response); } //GET using (var client = new WebClient()) { var responseString = client.DownloadString("http://www.example.com/recepticle.aspx"); }