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小时内与您取得联系。