NET (C#) 中,發送 HTTP GET 和 POST 請求可以通過多種方式實現,主要依賴于 .NET Framework 或 .NET Core/5+ 的版本。.NET中提供了多種方法來發送HTTP請求,每種方法都有其優缺點。選擇哪種方法取決于具體需求和環境。
HttpClient 是 .NET 中處理 HTTP 請求的現代方法。它是線程安全的,支持異步操作,并且可以用于多個請求。
適用平臺:.NET Framework 4.5+, .NET Standard 1.1+, .NET Core 1.0+
其它平臺的移植版本可以通過Nuget來安裝。(Nuget使用方法:VS(Visual Studio)中Nuget的使用-CJavaPy)
命名空間:using System.Net.Http;
HttpClient推薦使用單一實例共享使用,發關請求的方法推薦使用異步的方式,代碼如下,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
namespace ConsoleApplication
{
class Program
{
private static readonly HttpClient client=new HttpClient();
static void Main(string[] args)
{
//發送Get請求
var responseString=await client.GetStringAsync("http://www.example.com/recepticle.aspx");
//發送Post請求
var values=new Dictionary
{
{ "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();
}
}
}
2、使用第三方類庫
除了上述方法,還有許多第三方庫可以用于發送HTTP請求,例如 RestSharp 和 Flurl。這些庫通常提供更高級的功能,例如支持多種身份驗證方法和自動重試機制。
1)Flurl.Http(可以通過Nuget來安裝)
Flurl.Http 是一個在 .NET 環境下使用的流行的 HTTP 客戶端庫。它提供了一個簡潔的 API 來創建 HTTP 請求,并支持異步操作。Flurl.Http 使得發送 HTTP 請求、接收響應、處理異常和解析數據變得非常簡單。
命名空間:using Flurl.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Flurl.Http;
namespace ConsoleApplication
{
class Program
{
public static async Task Main(string[] args)
{
// 示例URL
string getUrl="https://example.com";
string postUrl="https://example.com/post";
// 發送GET請求
string htmlContent=await GetHtmlAsync(getUrl);
Console.WriteLine("GET請求結果:");
Console.WriteLine(htmlContent);
// 發送POST請求
var postData=new { Name="John", Age=30 };
var postResponse=await PostJsonAsync<object>(postUrl, postData);
Console.WriteLine("POST請求結果:");
Console.WriteLine(postResponse);
// 發送帶有查詢參數和頭信息的GET請求
string htmlContentWithHeaders=await GetHtmlWithHeadersAsync(getUrl);
Console.WriteLine("帶查詢參數和頭信息的GET請求結果:");
Console.WriteLine(htmlContentWithHeaders);
// 安全地發送GET請求
string safeHtmlContent=await SafeRequestAsync(getUrl);
Console.WriteLine("安全GET請求結果:");
Console.WriteLine(safeHtmlContent);
}
public static async Task<string> GetHtmlAsync(string url)
{
return await url.GetStringAsync();
}
public static async Task<TResponse> PostJsonAsync<TResponse >(string url, object data)
{
return await url
.PostJsonAsync(data)
.ReceiveJson<TResponse>();
}
public static async Task<string> GetHtmlWithHeadersAsync(string url)
{
return await url
.SetQueryParams(new { param1="value1", param2="value2" })
.WithHeader("Accept", "application/json")
.GetStringAsync();
}
public static async Task<string> SafeRequestAsync(string url)
{
try
{
return await url.GetStringAsync();
}
catch (FlurlHttpException ex)
{
return "HTTP Error: " + ex.Message;
}
catch (Exception ex)
{
return "General Error: " + ex.Message;
}
}
}
}
2)RestSharp(可以通過Nuget來安裝)
RestSharp 是一個用于在 .NET 中發送 HTTP 請求的簡單 REST 和 HTTP API 客戶端。它可以用于構建和發送各種 HTTP 請求,并處理響應。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
//發送Get和Post請求
RestClient client=new RestClient("http://example.com");//指定請求的url
RestRequest req=new RestRequest("resource/{id}", Method.GET);//指定請求的方式,如果Post則改成Method.POST
request.AddParameter("name", "value"); // 添加參數到 URL querystring
request.AddUrlSegment("id", "123"); //替換上面指定請求方式中的{id}參數
//req.AddBody(body); /*如發送post請求,則用req.AddBody ()指定body內容*/
//發送請求得到請求的內容
//如果有header可以使用下面方法添加
//request.AddHeader("header", "value");
IRestResponse response=client.Execute(request);
//上傳一個文件
//request.AddFile("file", path);
var content=response.Content; // 未處理的content是string
//還可以下面幾種方式發送請求
//發送請求,反序列化請求結果
IRestResponse response2=client.Execute(request);
var name=response2.Data.Name;
//發送請求下載一個文件,并保存到path路徑
client.DownloadData(request).SaveAs(path);
// 簡單發送異步請求
await client.ExecuteAsync(request);
// 發送異常請求并且反序列化結果
var asyncHandle=client.ExecuteAsync(request, response=> {
Console.WriteLine(response.Data.Name);
});
//終止異步的請求
asyncHandle.Abort();
}
}
}
較舊的方法,現在通常推薦使用 HttpClient。但在一些舊項目或特定場景下,WebRequest 和 WebResponse 仍然有用。
適用平臺:.NET Framework 1.1+, .NET Standard 2.0+, .NET Core 1.0+
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO; // for StreamReader
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
//發送Get請求
var request=(HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var response=(HttpWebResponse)request.GetResponse();
var responseString=new StreamReader(response.GetResponseStream()).ReadToEnd();
//發送Post請求
var request=(HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData="thing1=hello";
postData +="&thing2=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();
}
}
}
C#中,WebClient類提供了一個簡單的方法來發送和接收數據到和從一個URI(如一個網頁或Web服務)上。
適用平臺:.NET Framework 1.1+, .NET Standard 2.0+, .NET Core 2.0+
給定 URL 發出 GET 請求
使用 XMLHttpRequest 對象調用 Web API 向給定的 url 發送 GET 請求.
onload 方法通過調用給定的callback來處理事件responseText。
onerror 方法通過運行提供的函數來處理事件 err。
省略第三個參數,默認情況下 err 將錯誤記錄到控制臺的 error 流中。
JavaScript
const httpGet=(url, callback, err=console.error)=> { const request=new XMLHttpRequest(); request.open('GET', url, true); request.onload=()=> callback(request.responseText); request.onerror=()=> err(request); request.send();};
示例
httpGet( 'https://jsonplaceholder.typicode.com/posts/1', console.log); /*Logs: { "userId": 1, "id": 1, "title": "測試", "body": "返回響應內容"}*/
更多內容請訪問我的網站:https://www.icoderoad.com
● Web Server:
1.Protocol [http]:
○ 若為HTTP協議可以不填寫(默認為HTTP);
○ 若為HTTPS協議可以填寫“https”;還可以為FILE協議(本地文件傳輸協議);
2.Server Name or IP:
HTTP/Web服務器的域名或IP地址,本機可以使用localhost或127.0.0.1表示;
3.Port Number:
HTTP/Web服務器的監聽端口,若為HTTP協議,默認端口為80;若為HTTPs協議,默認端口為443。
使用默認端口可以不填,非默認端口必填。
● HTTP Request:
1.Method:
請求方法,測試GET請求,請選擇“GET”。
2.Path:
HTTP請求行中的request-target,可以使用絕對地址或相對地址。
比如: http://www.test.com/ecshop/index.php (絕對地址) /ecshop/index.php(相對地址)
注意: 若使用絕對地址,則會覆蓋“Web Server”中的配置。
3.Content-encoding:
通常用于在發送POST、PUT、PATCH請求時對message-body進行內容編碼,以防止請求出現亂碼或服務器無法正確處理請求。
注意其與請求的首部字段“Content-encoding”無關。
4.Redirect Automatically:
自動重定向。在JMeter中不記錄重定向的過程,只能看到最終的重定向請求。
5.Follow Redirects:
跟隨重定向。在JMeter會詳細記錄重定向的過程,可以看到多個重定向請求。其中4與5是互斥的。
比如,使用http://www.sina.com.cn/訪問新浪,會有一次重定向:
○ 第一次請求: GET http://www.sina.com.cn/ 重定向返回: Location: https://www.sina.com.cn/
○ 第二次請求: GET https://www.sina.com.cn/
若設置自動重定向,在查看結果樹中只能看到最終的請求:GET https://www.sina.com.cn/
若設置跟隨重定向,可以看到全部的兩次請求。
6.Use KeepAlive:
勾選在請求中加入首部字段“Connection: Keep-Alive”,否則設置為“Connection: Close”,默認為勾選。
7.Use multipart/form-data:
是否以multipart/form-data傳輸message-body。
8.Browser-compatible headers:
勾選此項,在使用multipart/form-data時,會抑止Content-Type與Content-Transfer-Encoding首部字段,僅發送Content-Disposition首部字段。
▲ 測試案例說明
1. 接口說明:
查詢被購買商品的總金額接口
2. 請求方式:
HTTP GET請求
3.接口地址:
/ecshop/upload/goods.php
4. 請求參數:
1) 輸入參數:
2) 請求示例:
GET
/ecshop/upload/goods.php?act=price&id=9&attr=227&number=1&1551081863462462
HTTP/1.1
Accept: */*
X-HttpWatch-RID: 22945-10042
Referer: http://localhost/ecshop/upload/goods.php?id=9
Accept-Language: zh-Hans-CN,zh-Hans;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0)
like
Gecko
Host: localhost
Connection: Keep-Alive
Cookie: ECS[history]=9; ECS[visit_times]=2;
ECS_ID=2a50bfdc24b5443814e73a5783912e21a55af811
5. 返回參數:
1) 響應參數:
2) 響應實例:
HTTP/1.1 200 OK
Date: Mon, 25 Feb 2019 08:16:27 GMT
Server: Apache/2.2.4 (Win32) PHP/5.2.4
X-Powered-By: PHP/5.2.4
Cache-control: private
Content-Length: 50
Keep-Alive: timeout=5, max=86
Connection: Keep-Alive
Content-Type: text/html; charset=utf-8
{"err_msg":"","result":"\uffe52298\u5143","qty":1}
▲ 測試步驟
1.在“Test Plan”節點上右鍵,選擇Add-->Threads(users)-->Thread Group;
2.在“Thread Group”節點上右鍵,選擇Add-->Sampler-->HTTP Request;
3.在“HTTP Request”節點上右鍵,選擇Add-->Listener-->View Results Tree;
4.選中“HTTP Request”對HTTP請求進行配置;
5.點擊“Save”,保存測試計劃;
6.點擊“Start”,運行JMeter測試。
HTTP GET請求的參數有兩種基本的配置方法:
1. 放在Path配置項中:
2. 放在Parameters選項卡中:
*請認真填寫需求信息,我們會在24小時內與您取得聯系。