首页 > 解决方案 > 当发送带有字节 [] 的 HTTP POST 时,服务器响应为 System.Byte[]

问题描述

我正在尝试使用 curl 将一个简单的 json 转换为用 C# 编写的字节 [] 发送到一个 Ubuntu 系统,该 curl 会命中一个用 Golang 编写的 HTTP 侦听器。问题是正在发送的内容似乎是 System.Byte[] 而不是可以解释为字节 [] 的内容。我对转换后的字节数组进行了 Encoding.UTF8.GetString 并且它确实返回正确,因此我尝试发送的内容或方式丢失了一些东西。

C# webforms 后端代码

public class TestSID
    {
        public string Number { get; set; }
       
    }
    public string sid { get; set; }
    public byte[] bytedata { get; set; }

    protected void Button1_Click(object sender, EventArgs e)
    {
        TestSID sid = new TestSID();
        sid.Number = Number.Text;

        string stringdata = JsonConvert.SerializeObject(sid);
        byte[] bytedata = Encoding.UTF8.GetBytes(stringdata);
        SSHSubmits.SIDSubmitByte(bytedata);                     
    }
}

发送到运行 HTTP 服务器的 Ubuntu 服务器

public static void SIDSubmitByte(byte[] fromSource)
    {
        using (var sshClient = ClientCreate())
        {

            sshClient.Connect();
             ByteArrayContent byteContent = new ByteArrayContent(fromSource);
            string consortiumPostAddr = "http://127.0.0.1:42069/incoming/1/1/testsid";
            SshCommand curlcmd = sshClient.CreateCommand("echo -e " + fromSource + " " + "| "  + "curl --request POST --data-binary " + "@- " + consortiumPostAddr);
            curlcmd.Execute();
            sshClient.Disconnect();
        }
    }

Golang POST Handler 案例

case "testsid":
    fmt.Printf("SSH TestSID Connected")
    fmt.Println("The incoming is", body)
    err := json.Unmarshal(body, &testSID)
    if err != nil {
                    fmt.Println(err)
                     if e, ok := err.(*json.SyntaxError); ok {
    log.Printf("syntax error at byte offset %d", e.Offset)
}
log.Printf("response: %q", body)
            }
            getNumber := testSID.Number
            if err != nil {
            fmt.Println(err)
            }
            fmt.Println("The number is", getNumber)
            TestSID(getNumber)
            return 200, []byte("TestSID Complete")

发送时的结果

SSH TestSID 已连接传入的是 [83 121 115 116 101 109 46 66 121 116 101 91 93 10] 无效字符“S”寻找值的开头 2021/06/09 10:16:42 字节偏移量 1 处的语法错误 1 ​​2021/ 06/09 10:16:42响应:“System.Byte[] \n”无效字符 'S' 寻找值的开头 数字已连接到 TestSID DB strconv.Atoi:解析“”:无效语法

使用https://onlinestringtools.com/convert-bytes-to-string我发现 [83 121 115 116 101 109 46 66 121 116 101 91 93 10] = 错误:错误:检测到无效的 UTF-8

标签: c#http

解决方案


当你这样做

    SshCommand curlcmd = sshClient.CreateCommand("echo -e " + fromSource + " " + "| "  + "curl --request POST --data-binary " + "@- " + consortiumPostAddr);

您要求 C# 创建fromSource可用于字符串连接的字符串表示形式。它通过调用ToString().

由于 'byte[]' 没有 ToString 实现,它沿着继承树向下并最终object.ToString()返回类型名称。在您的情况下为“System.Byte []”。

为了让它工作,您应该使用适当的编码自己将字节数组转换为字符串。如果你想要 UTF-8,你可以这样做

string fromSourceAsString = System.Text.Encoding.UTF8.GetString(fromSource);

如果您的字节数组包含不容易表示为字符串的二进制数据,您可以考虑在发送它之前对其进行 base64 编码并在接收端对其进行解码。


推荐阅读