C# Http request interface Get / Post

Table of contents

I. Overview

2. Create Web API 

3. HttpRequestHelper

3. Test

Finish


I. Overview

Get and post requests were first used as a communication protocol for interacting HTML and forms between browsers and servers, and were later widely extended to the definition of interface formats. So far, get / post requests are still used in major In the website, for example, when the user logs in, call get/post to request the user name and password to be sent to the server, and the server will judge whether the user is allowed to log in, and then return the result to the browser, thus realizing the login function. In later PC software development, get/post requests are occasionally used. As a programmer, the http protocol is also a knowledge point that we must learn.

2. Create Web API 

Create a web api project to be used as an interface for later testing. For how to create a project with Web API, you can refer to the tutorial I wrote before:

C# ASP.NET Web Core API (.NET 6.0)_Xiong Siyu's Blog-CSDN Blog

According to the above tutorial, after adding a ValuesController interface, I make some changes here

default:

After modification:

 Delete the two classes related to weather forecast added by default

The configuration of launchSettings.json is as follows. In applicationUrl, yours may be different from mine. This is a link for external access. There are two interfaces, one is https, the other is http, the port numbers are different, and the ip part is used to limit Logged in, if the developer is the owner, use 0.0.0.0 instead

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:10090",
      "sslPort": 44385
    }
  },
  "profiles": {
    "WebApplication1": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": false,
      "launchUrl": "swagger",
      "applicationUrl": "https://localhost:7281;http://localhost:5252",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Modify the ValuesController code as follows

using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ValuesController : ControllerBase
    {
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        [HttpPost]
        public string Post([FromForm] string json)
        {
            Console.WriteLine(json);

            return "hello, good afternoon";
        }
    }
}

Start the project, then test it with Postman

1. Get interface

2. Post interface

If the corresponding result is returned, it is successful. 

3. HttpRequestHelper

Create a new console project and add a class HttpRequestHelper

HttpRequestHelper code

using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;

public class HttpRequestHelper
{
    /// <summary>
    /// Get请求
    /// </summary>
    /// <param name="url">请求url</param>
    /// <returns></returns>
    public static Task<string> Get(string url)
    {
        var task = Task.Run(() =>
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "GET";
            req.Timeout = 5000;

            if (req == null || req.GetResponse() == null)
                return string.Empty;

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            if (resp == null)
                return string.Empty;

            using (Stream stream = resp.GetResponseStream())
            {
                //获取内容
                using (StreamReader reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            }
        });
        return task;
    }

    /// <summary>
    /// 指定Post地址使用Get 方式获取全部字符串
    /// </summary>
    /// <param name="url">请求后台地址</param>
    /// <returns></returns>
    public static Task<string> Post(string url)
    {
        var task = Task.Run(() =>
        {
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.Timeout = 5000;

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        });
        return task;
    }

    /// <summary>
    /// Post请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="postData"></param>
    /// <returns></returns>
    public static Task<string> Post(string url, object postData)
    {
        var task = Task.Run(() =>
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/json";
            req.Timeout = 5000;

            if (req == null)
                return string.Empty;

            byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(postData));
            //注意:无需手动指定长度 (否则可能会报流未处理完就关闭的异常,因为ContentLength时候会比真实post数据长度大)
            //req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
            }

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            if (resp == null)
                return string.Empty;

            using (Stream stream = resp.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
        });
        return task;
    }

    /// <summary>
    /// 指定Post地址使用Get 方式获取全部字符串
    /// </summary>
    /// <param name="url">请求后台地址</param>
    /// <returns></returns>
    public static Task<string> Post(string url, Dictionary<string, string> dic)
    {
        var task = Task.Run(() =>
        {
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            //req.ContentType = "application/json";
            req.Timeout = 5000;

            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        });
        return task;
    }
}

Regarding the assignment of req.ContentType, the common usages are as follows

/// <summary>
/// HTTP 内容类型(Content-Type)
/// </summary>
public class HttpContentType
{
    /// <summary>
    /// 资源类型:普通文本
    /// </summary>
    public const string TEXT_PLAIN = "text/plain";

    /// <summary>
    /// 资源类型:JSON字符串
    /// </summary>
    public const string APPLICATION_JSON = "application/json";

    /// <summary>
    /// 资源类型:未知类型(数据流)
    /// </summary>
    public const string APPLICATION_OCTET_STREAM = "application/octet-stream";

    /// <summary>
    /// 资源类型:表单数据(键值对)
    /// </summary>
    public const string WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";

    /// <summary>
    /// 资源类型:表单数据(键值对)。编码方式为 gb2312
    /// </summary>
    public const string WWW_FORM_URLENCODED_GB2312 = "application/x-www-form-urlencoded;charset=gb2312";

    /// <summary>
    /// 资源类型:表单数据(键值对)。编码方式为 utf-8
    /// </summary>
    public const string WWW_FORM_URLENCODED_UTF8 = "application/x-www-form-urlencoded;charset=utf-8";

    /// <summary>
    /// 资源类型:多分部数据
    /// </summary>
    public const string MULTIPART_FORM_DATA = "multipart/form-data";
}

About HttpWebRequest, you can refer to Microsoft's official documentation

HttpWebRequest 类 (System.Net) | Microsoft Learn

3. Test

1. Get request

Add the following code in the Program class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HttpTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Test();

            Console.ReadKey();
        }

        static async void Test()
        {
            string url = "http://localhost:5252/Values";

            try
            {
                string result = await HttpRequestHelper.Get(url);
                Console.WriteLine(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine("错误:\n{0}", ex.Message);
            }
        }
    }
}

run:

 Write the address wrong on purpose and execute it again to catch the error of "unable to connect to the server"

2. Post request

code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HttpTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Test();

            Console.ReadKey();
        }

        static async void Test()
        {
            string url = "http://localhost:5252/Values";

            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("json", "你好");

            try
            {
                string result = await HttpRequestHelper.Post(url, dic);
                Console.WriteLine(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine("错误:\n{0}", ex.Message);
            }
        }
    }
}

run:

When using the Post interface, it should be noted that the name of the parameter must be exactly the same as the name of the web api parameter. For example, the parameter name of the current post interface is "json"

Then the key-value pair added in dic, the key must also be "json", if not, you will not be able to access the post interface

Finish

If this post is helpful to you, please follow + like + leave a message, or if you have any questions, you can also send me a private message.

end

Guess you like

Origin blog.csdn.net/qq_38693757/article/details/131330883