怪奇物语

怪奇物语

首页 新随笔 联系 管理

C#中如何模拟一个post请求

使用HttpClient代替。以下是修改后的代码示例:

using System;
using System.Net.Http;
using System.Text.Json;

class HttpPostExample
{
    private async Task<string> HttpPost(string Url, object postData)
    {
        string postDataStr = JsonSerializer.Serialize(postData);
        HttpClient client = new HttpClient();
        StringContent content = new StringContent(postDataStr, Encoding.UTF8, "application/json");
        HttpResponseMessage response = await client.PostAsync(Url, content);
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();
        return responseBody;
    }

    public async void CallHttpPostMethod()
    {
        string url = "http://www.example.com";
        object postData = new { param1 = "value1", param2 = "value2" };
        string response = await HttpPost(url, postData);
        Console.WriteLine(response);
    }
}

在上面的代码中,我们使用HttpClient类来发送POST请求。我们创建了一个名为HttpPostExample的类,并在其中定义了一个名为CallHttpPostMethod的方法。该方法调用了HttpPost方法,并将其结果打印到控制台。
请注意,我们将HttpPost方法的返回类型更改为Task,并使用await关键字异步调用client.PostAsync方法。我们还使用StringContent类将postData对象序列化为JSON字符串,并将其传递给HttpClient对象。

GET,PUT,DELETE的请求

要扩展GET、PUT和DELETE请求,您可以使用C#中的HttpClient类。以下是一个示例代码,它演示了如何使用HttpClient类来模拟GET、PUT和DELETE请求:

using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

class HttpExample
{
    private async Task<string> HttpGet(string Url)
    {
        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(Url);
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();
        return responseBody;
    }

    private async Task<string> HttpPut(string Url, object postData)
    {
        string postDataStr = JsonSerializer.Serialize(postData);
        HttpClient client = new HttpClient();
        StringContent content = new StringContent(postDataStr, Encoding.UTF8, "application/json");
        HttpResponseMessage response = await client.PutAsync(Url, content);
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();
        return responseBody;
    }

    private async Task<string> HttpDelete(string Url)
    {
        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.DeleteAsync(Url);
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();
        return responseBody;
    }

    public async void CallHttpMethods()
    {
        string getUrl = "http://www.example.com";
        string putUrl = "http://www.example.com";
        string deleteUrl = "http://www.example.com";

        string getResponse = await HttpGet(getUrl);
        Console.WriteLine(getResponse);

        object putData = new { param1 = "value1", param2 = "value2" };
        string putResponse = await HttpPut(putUrl, putData);
        Console.WriteLine(putResponse);

        string deleteResponse = await HttpDelete(deleteUrl);
        Console.WriteLine(deleteResponse);
    }
}

在上面的代码中,我们使用HttpClient类来发送GET、PUT和DELETE请求。我们创建了一个名为HttpExample的类,并在其中定义了一个名为CallHttpMethods的方法。该方法调用了HttpGet、HttpPut和HttpDelete方法,并将其结果打印到控制台。
请注意,我们使用await关键字异步调用client.GetAsync、client.PutAsync和client.DeleteAsync方法。我们还使用StringContent类将postData对象序列化为JSON字符串,并将其传递给HttpClient对象。
希望这可以帮助您!

GET请求如何传递参数-查询参数

要在GET请求中传递参数,您可以使用HttpClient类。以下是修改后的代码示例,它演示了如何使用HttpClient类来模拟带有参数的GET请求:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class HttpExample
{
    private async Task<string> HttpGet(string Url, object parameters)
    {
        HttpClient client = new HttpClient();
        string queryString = "";
        if (parameters != null)
        {
            foreach (var property in parameters.GetType().GetProperties())
            {
                if (queryString.Length > 0)
                {
                    queryString += "&";
                }
                queryString += $"{property.Name}={property.GetValue(parameters)}";
            }
        }
        HttpResponseMessage response = await client.GetAsync($"{Url}?{queryString}");
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();
        return responseBody;
    }

    public async void CallHttpGetMethod()
    {
        string url = "http://www.example.com";
        object parameters = new { param1 = "value1", param2 = "value2" };
        string response = await HttpGet(url, parameters);
        Console.WriteLine(response);
    }
}

在上面的代码中,我们使用HttpClient类来发送GET请求。我们创建了一个名为HttpExample的类,并在其中定义了一个名为CallHttpGetMethod的方法。该方法调用了HttpGet方法,并将其结果打印到控制台。
请注意,我们将HttpGet方法的第二个参数类型更改为object,这样就可以接受任何类型的数据。然后,我们使用反射来获取参数对象的属性,并将其转换为查询字符串,然后将其附加到URL中。

get请求,传递restful类型的参数

要在GET请求中传递RESTful类型的参数,您可以使用HttpClient类。以下是修改后的代码示例,它演示了如何使用HttpClient类来模拟带有RESTful类型参数的GET请求:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class HttpExample
{
    private async Task<string> HttpGet(string Url, object parameters)
    {
        HttpClient client = new HttpClient();
        string queryString = "";
        if (parameters != null)
        {
            foreach (var property in parameters.GetType().GetProperties())
            {
                if (queryString.Length > 0)
                {
                    queryString += "/";
                }
                queryString += $"{property.GetValue(parameters)}";
            }
        }
        HttpResponseMessage response = await client.GetAsync($"{Url}/{queryString}");
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();
        return responseBody;
    }

    public async void CallHttpGetMethod()
    {
        string url = "http://www.example.com";
        object parameters = new { id = 1, firstName = "John", lastName = "Doe" };
        string response = await HttpGet(url, parameters);
        Console.WriteLine(response);
    }
}

在上面的代码中,我们使用HttpClient类来发送GET请求。我们创建了一个名为HttpExample的类,并在其中定义了一个名为CallHttpGetMethod的方法。该方法调用了HttpGet方法,并将其结果打印到控制台。
请注意,我们将HttpGet方法的第二个参数类型更改为object,这样就可以接受任何类型的数据。然后,我们使用反射来获取参数对象的属性,并将其转换为RESTful类型的参数,然后将其附加到URL中。

设置请求头,模拟chrome浏览器发出的请求

要在类里面设置请求头,您可以使用HttpClient类。以下是修改后的代码示例,它演示了如何在类中设置请求头:

using System;
using System.Net.Http;
using System.Text.Json;

namespace HttpReq
{
    public class Http
    {
        private readonly string url;
        private readonly HttpClient client;

        public Http(string url)
        {
            this.url = url;
            this.client = new HttpClient();
            this.client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
        }

        public async Task<string> HttpGet()
        {
            HttpResponseMessage response = await this.client.GetAsync(this.url);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            return responseBody;
        }
    }
}

在上面的代码中,我们使用HttpClient类来发送GET请求。我们创建了一个名为Http的类,并在其中定义了一个名为HttpGet的方法。该方法调用了HttpClient.GetAsync方法,并将其结果返回。
请注意,我们在类的构造函数中设置了请求头。我们使用HttpClient.DefaultRequestHeaders.Add方法将User-Agent请求头添加到HttpClient对象中。
希望这可以帮助您!

返回的内容解析成json格式

要将HttpGet返回的内容解析为JSON格式,您可以使用System.Text.Json命名空间中的JsonSerializer.Deserialize方法。以下是修改后的代码示例:

using System;
using System.Net.Http;
using System.Text.Json;

namespace HttpReq
{
    public class Http
    {
        private readonly string url;
        private readonly HttpClient client;

        public Http(string url)
        {
            this.url = url;
            this.client = new HttpClient();
            this.client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
        }

        public async Task<JsonElement> HttpGet()
        {
            HttpResponseMessage response = await this.client.GetAsync(this.url);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            JsonDocument document = JsonDocument.Parse(responseBody);
            return document.RootElement;
        }
    }
}

在上面的代码中,我们使用HttpClient类来发送GET请求。我们创建了一个名为Http的类,并在其中定义了一个名为HttpGet的方法。该方法调用了HttpClient.GetAsync方法,并将其结果解析为JSON格式。
请注意,我们将HttpGet方法的返回类型更改为JsonElement,并使用JsonDocument.Parse方法将HTTP响应解析为JSON格式。然后,我们返回根元素。

获取返回的json中的字段

要获取JSON对象中的title字段,您可以使用JsonElement.GetProperty方法。以下是修改后的代码示例:

var res4=await http.HttpPost(new { title = "name 3",id=3 });
var res4Json = JsonDocument.Parse(res4).RootElement;

string title = res4Json.GetProperty("title").GetString();
System.Console.WriteLine(title);

在上面的代码中,我们使用JsonDocument.Parse方法将HTTP响应解析为JSON格式。然后,我们使用JsonElement.GetProperty方法获取title属性,并使用GetString方法将其转换为字符串。
希望这可以帮助您!

遍历JSON数组

要遍历JSON数组,您可以使用JsonElement.EnumerateArray方法。以下是修改后的代码示例:

var vehicleHttp = new Http("http://localhost:3000/verhicles",token);
var res2 =await vehicleHttp.HttpGet();

var resJson2 = JsonDocument.Parse(res2).RootElement;
var vehicles = resJson2.GetProperty("vehicles");


foreach (JsonElement vehicle in vehicles.EnumerateArray())
{
    string make = vehicle.GetProperty("make").GetString();
    string model = vehicle.GetProperty("model").GetString();
    int year = vehicle.GetProperty("year").GetInt32();
    System.Console.WriteLine($"{year} {make} {model}");
}

在上面的代码中,我们使用JsonDocument.Parse方法将HTTP响应解析为JSON格式。然后,我们使用JsonElement.GetProperty方法获取vehicles属性,并使用JsonElement.EnumerateArray方法遍历所有元素。
在循环中,我们使用JsonElement.GetProperty方法获取每个车辆的属性,并使用GetString和GetInt32方法将其转换为字符串和整数。

header里面动态添加一个token字段

要在HTTP请求的头部中动态添加一个token字段,您可以使用HttpClient类。以下是修改后的代码示例:

using System;
using System.Net.Http;
using System.Text.Json;

namespace HttpReq
{
    public class Http
    {
        private readonly string url;
        private readonly HttpClient client;

        public Http(string url, string token)
        {
            this.url = url;
            this.client = new HttpClient();
            this.client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
            this.client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
        }

        public async Task<JsonElement> HttpGet()
        {
            HttpResponseMessage response = await this.client.GetAsync(this.url);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            JsonDocument document = JsonDocument.Parse(responseBody);
            return document.RootElement;
        }
    }
}

在上面的代码中,我们使用HttpClient类来发送GET请求。我们创建了一个名为Http的类,并在其中定义了一个名为HttpGet的方法。该方法调用了HttpClient.GetAsync方法,并将其结果解析为JSON格式。
请注意,我们将Http类的构造函数中添加了一个token参数,用于动态设置请求头中的Authorization字段。我们使用HttpClient.DefaultRequestHeaders.Add方法将Authorization请求头添加到HttpClient对象中。

打印header

上面的代码定义了一个名为Http的类,该类包含一个构造函数,用于初始化HttpClient对象。在构造函数中,我们使用HttpClient.DefaultRequestHeaders.Add方法将User-Agent和token请求头添加到HttpClient对象中。
要打印请求头,请使用以下代码:

using System;
using System.Net.Http;
using System.Text.Json;

namespace HttpReq
{
    public class Http
    {
        private readonly string url;
        private readonly HttpClient client;

        public Http(string url, string token = "")
        {
            this.url = url;
            this.client = new HttpClient();
            this.client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
            this.client.DefaultRequestHeaders.Add("token", token);
        }

        public async Task<JsonElement> HttpGet()
        {
            HttpResponseMessage response = await this.client.GetAsync(this.url);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            JsonDocument document = JsonDocument.Parse(responseBody);
            return document.RootElement;
        }

        public void PrintHeaders()
        {
            foreach (var header in this.client.DefaultRequestHeaders)
            {
                Console.WriteLine($"{header.Key}: {string.Join(",", header.Value)}");
            }
        }
    }
}

在上面的代码中,我们添加了一个名为PrintHeaders的方法,该方法用于打印请求头。我们使用HttpClient.DefaultRequestHeaders属性获取请求头,并使用foreach循环遍历所有请求头。
希望这可以帮助您!

posted on 2024-01-15 22:01  超级无敌美少男战士  阅读(170)  评论(0)    收藏  举报