c# - 将 csv 内容发布到 HTTP API C#

标签 c# api http post

我再次成为 C# 新手,我强制自己进行一些练习并将理论付诸实践。我目前正在开发一个小型应用程序,用于将大型 csv 文件(2000 多行)的内容发布到 http API。 API 的格式为

https://mydomain.com//api/dump/?
             t = <app_token> // provided by auth function
             &[
                xml = <device_data_package> 
                OR
                csv = <device_data_package>

我的问题是,如何将 csv 内容传递到 http POST 的正文?感谢您的反馈和帮助。

最佳答案

就像其他答案所说的那样,假设您有打开文件并读取内容的代码,您的 CSV 文件将包含一个字符串,其中的值以逗号分隔。您可以将其添加为 url 参数,以提供如下所示的内容:

https://mydomain.com//api/dump/?t=my_token&csv=my,values,from,my,csv,file,go,here

但是,url 的长度有限制。因此,如果您有除小 CSV 文件以外的任何内容,最好将 CSV 数据作为帖子正文发送,就像您在问题中提到的那样。

下面的方法可能会派上用场。它将一个对象作为参数并将其嵌入到 post 请求中,并以字符串形式返回响应。我一直在我的网站上使用它来将数据发送到外部服务。它是一个更大的类的一部分,因此我可能有太多的 using 语句。

你可以像这样使用它:

WebUtilities.Post("https://mydomain.com//api/dump/?t=my_token", "csv=" + contents_of_my_csv_file);

该方法如下所示:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Script.Serialization;
using System.Xml;

public static class WebUtilities
{
    public static string Post(string url, object postData)
    {
        HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url);

        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        bf.Serialize(ms, postData);

        byte[] data = ms.ToArray();

        httpWReq.Method = "POST";
        httpWReq.ContentType = "application/x-www-form-urlencoded";
        httpWReq.ContentLength = data.Length;

        using (Stream newStream = httpWReq.GetRequestStream())
        {
            newStream.Write(data, 0, data.Length);
        }

        HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();

        Stream stream = response.GetResponseStream();

        Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

        StreamReader streamReader = new StreamReader(stream, encode);

        string html = streamReader.ReadToEnd();

        response.Close();

        streamReader.Close();

        return html;
    }
}

关于c# - 将 csv 内容发布到 HTTP API C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26019802/

相关文章:

c# - Python 与 C# Twitter API 库

javascript - 不存在 'Access-Control-Allow-Origin' header 。 origin因此不允许访问

c# - Telerik RadUpload 浏览按钮移动到文本框下方

c# - for循环中的条件是否在每次迭代中都被评估?

amazon-web-services - AWS Lambda 中 id_token 与 access_token 使用的最佳实践

java - 无法向springboot发送http post请求

http - 转到 http POST 文件

c# - EF Core 添加迁移调试

c# - 用于查找被 {{ }} 包围的单词的正则表达式

json - 使用查询在 Golang 中处理 API?