C# HttpWebRequest使用 结合Flask作为后端进行展示
发布日期:2021-05-14 15:07:19 浏览次数:21 分类:精选文章

本文共 5665 字,大约阅读时间需要 18 分钟。

在C#中发送HTTP请求可以通过HttpWebRequest类来实现。以下是详细说明:

不带参数的GET请求

  • 创建请求:使用HttpWebRequest.Create方法创建请求对象。
  • 设置方法:指定HTTP方法为GET。
  • 发送请求:调用GetResponse方法获取WebResponse对象。
  • 读取响应内容:使用StreamReader读取响应流内容。
  • using System;
    using System.IO;
    using System.Net;
    namespace ConsoleApp1
    {
    class Program
    {
    static void Main(string[] args)
    {
    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://127.0.0.1:8001/test/");
    req.Method = "GET";
    HttpWebResponse res;
    try
    {
    res = (HttpWebResponse)req.GetResponse();
    }
    catch (WebException ex)
    {
    res = (HttpWebResponse)ex.Response;
    }
    StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
    string content = sr.ReadToEnd();
    Console.WriteLine(content);
    }
    }
    }

    带参数的GET请求

  • 创建参数字典:用于存储GET参数。
  • 拼接URL:将参数按格式追加到URL末尾。
  • 处理URL编码:确保特殊字符正确编码。
  • 发送请求并读取响应:与不带参数的GET请求类似操作。
  • using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    namespace http_test
    {
    class Program
    {
    static void Main(string[] args)
    {
    Dictionary
    param = new Dictionary
    ();
    param.Add("source", "D:/source/target.dicm");
    param.Add("operation", "1");
    param.Add("destination", "D:/destination/target.dicm");
    string url = "http://127.0.0.1:5000/test2";
    string result = HttpTest.GET(url, param);
    Console.WriteLine(result);
    }
    }
    public class HttpTest
    {
    public static string GET(string url, Dictionary
    param)
    {
    if (param != null)
    {
    StringBuilder queryBuilder = new StringBuilder(url.Contains("?") ? "" : "?");
    foreach (var item in param)
    {
    queryBuilder.Append(item.Key);
    queryBuilder.Append("=");
    queryBuilder.Append(System.Uri.EscapeUriComponent(item.Value));
    queryBuilder.Append("&");
    }
    url = queryBuilder.ToString().Substring(0, queryBuilder.Length - 1);
    }
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "GET";
    HttpWebResponse res;
    try
    {
    res = (HttpWebResponse)request.GetResponse();
    }
    catch (WebException ex)
    {
    res = (HttpWebResponse)ex.Response;
    }
    StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
    return sr.ReadToEnd();
    }
    }
    }

    Flask后端示例

    from flask import Flask, request, url_for
    from flask_restful import Api, Resource, reqparse
    import base64
    app = Flask(__name__)
    api = Api(app)
    class TestView(Resource):
    def get(self):
    return {"message": "Testing GET method"}
    def post(self):
    data = request.get_json()
    # Process the data
    return {"success": True}
    @app.route("/file", methods=["POST"])
    def fileUpload():
    file = request.files.get("file")
    if file:
    file_path = " uploaded_file.jpg "
    # Save file
    return file_path

    WinForm界面

  • 设计界面:创建用户界面,包含按钮和输入框。
  • 引用必要命名空间:确保所有必要的类被引用。
  • 调用HTTP方法:在按钮点击事件中调用之前编写的GET或POST方法。
  • 显示结果:在成功获取响应后显示结果。
  • client.cs:

    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Windows.Forms;
    namespace WFM_Test001
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://www.baidu.com");
    req.Method = HttpWebRequest.Method.Get;
    HttpWebResponse res;
    try
    {
    res = (HttpWebResponse)req.GetResponse();
    }
    catch (WebException ex)
    {
    res = (HttpWebResponse)ex.Response;
    }
    StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
    string result = sr.ReadToEnd();
    MessageBox.Show("结果:" + result);
    }
    private void button3_Click(object sender, EventArgs e)
    {
    string url = "http://127.0.0.1:5000/test";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = HttpWebRequest.Method.Get;
    HttpWebResponse res;
    try
    {
    res = (HttpWebResponse)request.GetResponse();
    }
    catch (WebException ex)
    {
    res = (HttpWebResponse)ex.Response;
    }
    StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
    string content = sr.ReadToEnd();
    MessageBox.Show("结果:" + content);
    }
    private void button2_Click(object sender, EventArgs e)
    {
    Dictionary
    param = new Dictionary
    ();
    param.Add("source", "D:/test.dcm");
    param.Add("operation", "1");
    param.Add("destination", "D:/destination/test.dcm");
    string url = "http://127.0.0.1:5000/test";
    string result = HttpTest.POST(url, "D:/1.png");
    MessageBox.Show("上传结果:" + result);
    }
    }
    }

    总结

    通过以上代码示例,可以在C#中实现与服务器交互的各种HTTP请求。理解每个步骤的目的和实现方式,是实现自定义API或脚本化任务的关键。建议根据具体需求调整请求方式和参数,确保URL编码的正确性和异常处理的有效性。

    上一篇:django在查找数据的时候根据添加的时间排序
    下一篇:vscode中使用c#

    发表评论

    最新留言

    很好
    [***.229.124.182]2025年04月09日 16时42分00秒