【发布时间】:2021-06-10 02:44:56
【问题描述】:
我正在尝试使用 curl 将一个简单的 json 转换为用 C# 编写的字节 [] 发送到一个 Ubuntu 系统,该系统会命中一个用 Golang 编写的 HTTP 侦听器。问题是发送的内容似乎是 System.Byte[] 而不是可以解释为字节 [] 的内容。我对转换后的字节数组进行了 Encoding.UTF8.GetString,它确实返回正确,所以我尝试发送的内容或方式丢失了一些东西。
C# 网络表单后端代码
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 处的语法错误 2021/06/09 10:16:42 回复:“System.Byte[]\n” 寻找值开头的无效字符“S” 号码是 连接到 TestSID 数据库 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
【问题讨论】: