组合字符串和 []byte 作为有效负载

我正在尝试发送一个 http 请求,其有效负载包含 2 个字符串和一个 [] 字节。有什么好的方法可以解决这个问题吗?我尝试过加密/解密(不起作用),将 []byte 转换为字符串(因为 []byte 是图像,所以不起作用)。

视觉表现:

字符串1 []字节字符串2


呼啦一阵风
浏览 92回答 1
1回答

陪伴而非守候

这是使用多部分请求的示例。我根据处理 JSON 文档的一段代码修改了它,因此其中可能存在一些错误,但它应该给您一个想法:&nbsp; &nbsp; &nbsp; &nbsp; body := bytes.Buffer{}&nbsp; &nbsp; &nbsp; &nbsp; writer := multipart.NewWriter(&body)&nbsp; &nbsp; &nbsp; &nbsp; hdr := textproto.MIMEHeader{}&nbsp; &nbsp; &nbsp; &nbsp; hdr.Set("Content-Type", "text/plain")&nbsp; &nbsp; &nbsp; &nbsp; part, _ := writer.CreatePart(hdr)&nbsp; &nbsp; &nbsp; &nbsp; part.Write(data1)&nbsp; &nbsp; &nbsp; &nbsp; hdr = textproto.MIMEHeader{}&nbsp; &nbsp; &nbsp; &nbsp; hdr.Set("Content-Type", <image type>)&nbsp; &nbsp; &nbsp; &nbsp; part, _ = writer.CreatePart(hdr)&nbsp; &nbsp; &nbsp; &nbsp; part.Write(imageData)&nbsp; &nbsp; &nbsp; &nbsp; ... // Add more parts if you need to&nbsp; &nbsp; &nbsp; &nbsp; writer.Close()&nbsp; &nbsp; &nbsp; &nbsp; request, _ := http.NewRequest(http.MethodPost, url, &body)&nbsp; &nbsp; &nbsp; &nbsp; request.Header.Set("Content-Type", fmt.Sprintf("multipart/mixed;boundary=%s", writer.Boundary()))&nbsp; &nbsp; &nbsp; &nbsp; hcli := http.Client{}&nbsp; &nbsp; &nbsp; &nbsp; rsp, err := hcli.Do(request)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go