Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
NET (C#) 中,發(fā)送 HTTP GET 和 POST 請(qǐng)求可以通過多種方式實(shí)現(xiàn),主要依賴于 .NET Framework 或 .NET Core/5+ 的版本。.NET中提供了多種方法來發(fā)送HTTP請(qǐng)求,每種方法都有其優(yōu)缺點(diǎn)。選擇哪種方法取決于具體需求和環(huán)境。
HttpClient 是 .NET 中處理 HTTP 請(qǐng)求的現(xiàn)代方法。它是線程安全的,支持異步操作,并且可以用于多個(gè)請(qǐng)求。
適用平臺(tái):.NET Framework 4.5+, .NET Standard 1.1+, .NET Core 1.0+
其它平臺(tái)的移植版本可以通過Nuget來安裝。(Nuget使用方法:VS(Visual Studio)中Nuget的使用-CJavaPy)
命名空間:using System.Net.Http;
HttpClient推薦使用單一實(shí)例共享使用,發(fā)關(guān)請(qǐng)求的方法推薦使用異步的方式,代碼如下,
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)
{
//發(fā)送Get請(qǐng)求
var responseString=await client.GetStringAsync("http://www.example.com/recepticle.aspx");
//發(fā)送Post請(qǐng)求
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、使用第三方類庫(kù)
除了上述方法,還有許多第三方庫(kù)可以用于發(fā)送HTTP請(qǐng)求,例如 RestSharp 和 Flurl。這些庫(kù)通常提供更高級(jí)的功能,例如支持多種身份驗(yàn)證方法和自動(dòng)重試機(jī)制。
1)Flurl.Http(可以通過Nuget來安裝)
Flurl.Http 是一個(gè)在 .NET 環(huán)境下使用的流行的 HTTP 客戶端庫(kù)。它提供了一個(gè)簡(jiǎn)潔的 API 來創(chuàng)建 HTTP 請(qǐng)求,并支持異步操作。Flurl.Http 使得發(fā)送 HTTP 請(qǐng)求、接收響應(yīng)、處理異常和解析數(shù)據(jù)變得非常簡(jiǎn)單。
命名空間: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";
// 發(fā)送GET請(qǐng)求
string htmlContent=await GetHtmlAsync(getUrl);
Console.WriteLine("GET請(qǐng)求結(jié)果:");
Console.WriteLine(htmlContent);
// 發(fā)送POST請(qǐng)求
var postData=new { Name="John", Age=30 };
var postResponse=await PostJsonAsync<object>(postUrl, postData);
Console.WriteLine("POST請(qǐng)求結(jié)果:");
Console.WriteLine(postResponse);
// 發(fā)送帶有查詢參數(shù)和頭信息的GET請(qǐng)求
string htmlContentWithHeaders=await GetHtmlWithHeadersAsync(getUrl);
Console.WriteLine("帶查詢參數(shù)和頭信息的GET請(qǐng)求結(jié)果:");
Console.WriteLine(htmlContentWithHeaders);
// 安全地發(fā)送GET請(qǐng)求
string safeHtmlContent=await SafeRequestAsync(getUrl);
Console.WriteLine("安全GET請(qǐng)求結(jié)果:");
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 是一個(gè)用于在 .NET 中發(fā)送 HTTP 請(qǐng)求的簡(jiǎn)單 REST 和 HTTP API 客戶端。它可以用于構(gòu)建和發(fā)送各種 HTTP 請(qǐng)求,并處理響應(yīng)。
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)
{
//發(fā)送Get和Post請(qǐng)求
RestClient client=new RestClient("http://example.com");//指定請(qǐng)求的url
RestRequest req=new RestRequest("resource/{id}", Method.GET);//指定請(qǐng)求的方式,如果Post則改成Method.POST
request.AddParameter("name", "value"); // 添加參數(shù)到 URL querystring
request.AddUrlSegment("id", "123"); //替換上面指定請(qǐng)求方式中的{id}參數(shù)
//req.AddBody(body); /*如發(fā)送post請(qǐng)求,則用req.AddBody ()指定body內(nèi)容*/
//發(fā)送請(qǐng)求得到請(qǐng)求的內(nèi)容
//如果有header可以使用下面方法添加
//request.AddHeader("header", "value");
IRestResponse response=client.Execute(request);
//上傳一個(gè)文件
//request.AddFile("file", path);
var content=response.Content; // 未處理的content是string
//還可以下面幾種方式發(fā)送請(qǐng)求
//發(fā)送請(qǐng)求,反序列化請(qǐng)求結(jié)果
IRestResponse response2=client.Execute(request);
var name=response2.Data.Name;
//發(fā)送請(qǐng)求下載一個(gè)文件,并保存到path路徑
client.DownloadData(request).SaveAs(path);
// 簡(jiǎn)單發(fā)送異步請(qǐng)求
await client.ExecuteAsync(request);
// 發(fā)送異常請(qǐng)求并且反序列化結(jié)果
var asyncHandle=client.ExecuteAsync(request, response=> {
Console.WriteLine(response.Data.Name);
});
//終止異步的請(qǐng)求
asyncHandle.Abort();
}
}
}
較舊的方法,現(xiàn)在通常推薦使用 HttpClient。但在一些舊項(xiàng)目或特定場(chǎng)景下,WebRequest 和 WebResponse 仍然有用。
適用平臺(tái):.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)
{
//發(fā)送Get請(qǐng)求
var request=(HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var response=(HttpWebResponse)request.GetResponse();
var responseString=new StreamReader(response.GetResponseStream()).ReadToEnd();
//發(fā)送Post請(qǐng)求
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類提供了一個(gè)簡(jiǎn)單的方法來發(fā)送和接收數(shù)據(jù)到和從一個(gè)URI(如一個(gè)網(wǎng)頁或Web服務(wù))上。
適用平臺(tái):.NET Framework 1.1+, .NET Standard 2.0+, .NET Core 2.0+
給定 URL 發(fā)出 GET 請(qǐng)求
使用 XMLHttpRequest 對(duì)象調(diào)用 Web API 向給定的 url 發(fā)送 GET 請(qǐng)求.
onload 方法通過調(diào)用給定的callback來處理事件responseText。
onerror 方法通過運(yùn)行提供的函數(shù)來處理事件 err。
省略第三個(gè)參數(shù),默認(rèn)情況下 err 將錯(cuò)誤記錄到控制臺(tái)的 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": "測(cè)試", "body": "返回響應(yīng)內(nèi)容"}*/
更多內(nèi)容請(qǐng)?jiān)L問我的網(wǎng)站:https://www.icoderoad.com
● Web Server:
1.Protocol [http]:
○ 若為HTTP協(xié)議可以不填寫(默認(rèn)為HTTP);
○ 若為HTTPS協(xié)議可以填寫“https”;還可以為FILE協(xié)議(本地文件傳輸協(xié)議);
2.Server Name or IP:
HTTP/Web服務(wù)器的域名或IP地址,本機(jī)可以使用localhost或127.0.0.1表示;
3.Port Number:
HTTP/Web服務(wù)器的監(jiān)聽端口,若為HTTP協(xié)議,默認(rèn)端口為80;若為HTTPs協(xié)議,默認(rèn)端口為443。
使用默認(rèn)端口可以不填,非默認(rèn)端口必填。
● HTTP Request:
1.Method:
請(qǐng)求方法,測(cè)試GET請(qǐng)求,請(qǐng)選擇“GET”。
2.Path:
HTTP請(qǐng)求行中的request-target,可以使用絕對(duì)地址或相對(duì)地址。
比如: http://www.test.com/ecshop/index.php (絕對(duì)地址) /ecshop/index.php(相對(duì)地址)
注意: 若使用絕對(duì)地址,則會(huì)覆蓋“Web Server”中的配置。
3.Content-encoding:
通常用于在發(fā)送POST、PUT、PATCH請(qǐng)求時(shí)對(duì)message-body進(jìn)行內(nèi)容編碼,以防止請(qǐng)求出現(xiàn)亂碼或服務(wù)器無法正確處理請(qǐng)求。
注意其與請(qǐng)求的首部字段“Content-encoding”無關(guān)。
4.Redirect Automatically:
自動(dòng)重定向。在JMeter中不記錄重定向的過程,只能看到最終的重定向請(qǐng)求。
5.Follow Redirects:
跟隨重定向。在JMeter會(huì)詳細(xì)記錄重定向的過程,可以看到多個(gè)重定向請(qǐng)求。其中4與5是互斥的。
比如,使用http://www.sina.com.cn/訪問新浪,會(huì)有一次重定向:
○ 第一次請(qǐng)求: GET http://www.sina.com.cn/ 重定向返回: Location: https://www.sina.com.cn/
○ 第二次請(qǐng)求: GET https://www.sina.com.cn/
若設(shè)置自動(dòng)重定向,在查看結(jié)果樹中只能看到最終的請(qǐng)求:GET https://www.sina.com.cn/
若設(shè)置跟隨重定向,可以看到全部的兩次請(qǐng)求。
6.Use KeepAlive:
勾選在請(qǐng)求中加入首部字段“Connection: Keep-Alive”,否則設(shè)置為“Connection: Close”,默認(rèn)為勾選。
7.Use multipart/form-data:
是否以multipart/form-data傳輸message-body。
8.Browser-compatible headers:
勾選此項(xiàng),在使用multipart/form-data時(shí),會(huì)抑止Content-Type與Content-Transfer-Encoding首部字段,僅發(fā)送Content-Disposition首部字段。
▲ 測(cè)試案例說明
1. 接口說明:
查詢被購(gòu)買商品的總金額接口
2. 請(qǐng)求方式:
HTTP GET請(qǐng)求
3.接口地址:
/ecshop/upload/goods.php
4. 請(qǐng)求參數(shù):
1) 輸入?yún)?shù):
2) 請(qǐng)求示例:
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. 返回參數(shù):
1) 響應(yīng)參數(shù):
2) 響應(yīng)實(shí)例:
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}
▲ 測(cè)試步驟
1.在“Test Plan”節(jié)點(diǎn)上右鍵,選擇Add-->Threads(users)-->Thread Group;
2.在“Thread Group”節(jié)點(diǎn)上右鍵,選擇Add-->Sampler-->HTTP Request;
3.在“HTTP Request”節(jié)點(diǎn)上右鍵,選擇Add-->Listener-->View Results Tree;
4.選中“HTTP Request”對(duì)HTTP請(qǐng)求進(jìn)行配置;
5.點(diǎn)擊“Save”,保存測(cè)試計(jì)劃;
6.點(diǎn)擊“Start”,運(yùn)行JMeter測(cè)試。
HTTP GET請(qǐng)求的參數(shù)有兩種基本的配置方法:
1. 放在Path配置項(xiàng)中:
2. 放在Parameters選項(xiàng)卡中:
*請(qǐng)認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。