将Curl上传示例转为VB.Net代码时遇400错误求排查
排查VB.Net转换Curl上传请求返回400 Bad Request的问题
问题根源分析
你的代码存在几个关键错误,导致API返回400请求错误:
- 字段名拼写与大小写不匹配:目标API的JSON字段是严格区分拼写和大小写的,你的代码里存在三处错误:
trasnmitter→ 正确应为transmitter(拼写少了字母m)filename→ 正确应为fileName(API要求驼峰命名)filecontentbase64→ 正确应为fileContentBase64(API要求驼峰命名)
- 文件内容处理错误:使用
ReadAllText读取文件再转UTF8字节,会破坏非UTF8编码文件的原始内容,应该直接读取文件字节流再转Base64 - 请求ContentLength设置错误:应该使用UTF8编码后的字节数组长度,而非原字符串长度(字符串长度和字节数可能不一致)
修正后的完整代码
1. 文件内容读取与Base64转换
' 直接读取文件原始字节,避免编码转换导致的内容损坏 Dim byt As Byte() = IO.File.ReadAllBytes(FullFileName) Dim Content As String = Convert.ToBase64String(byt)
2. 构建正确的请求体
' 构建请求体,修正所有字段名的拼写与大小写 Dim Dta As New Dictionary(Of String, Object) Dim Transmitter As New Dictionary(Of String, Object) From { {"username", USR}, {"password", PWD} } Dta.Add("transmitter", Transmitter) Dta.Add("simulateUpload", True) Dim FileListarray As New List(Of Object) From { New Dictionary(Of String, Object) From { {"fileName", "TEST_DataFile.txt"}, {"ContentType", "text/plain"}, {"fileContentBase64", Content} } } Dta.Add("files", FileListarray.ToArray) Dim Body As String = JsonConvert.SerializeObject(Dta, Formatting.Indented) Dim BodyBytes As Byte() = Encoding.UTF8.GetBytes(Body)
3. 发送请求并处理响应(完善错误排查)
' 构建请求并修正ContentLength设置 Dim URL As String = BaseURL & "/v2/Upload/FilesBase64" Dim WebRequest As Net.WebRequest = WebRequest.Create(URL) WebRequest.ContentType = "application/json" WebRequest.Method = "POST" WebRequest.ContentLength = BodyBytes.Length ' 使用字节数组的真实长度 ' 发送请求,Using语句自动释放资源 Using Stream As Stream = WebRequest.GetRequestStream() Stream.Write(BodyBytes, 0, BodyBytes.Length) End Using ' 获取响应,捕获WebException获取服务器错误详情 Dim ServerText As String = "" Try Using Response As WebResponse = WebRequest.GetResponse Using ResponseStream As New StreamReader(Response.GetResponseStream) ServerText = ResponseStream.ReadToEnd End Using End Using Catch ex As Net.WebException ' 读取服务器返回的错误详情,方便进一步排查 If ex.Response IsNot Nothing Then Using reader As New StreamReader(ex.Response.GetResponseStream()) Dim errorDetails = reader.ReadToEnd() ' 可在此处输出或记录errorDetails End Using End If End Try
额外建议
捕获WebException时读取服务器返回的错误详情,这能帮你精准定位剩余问题(比如权限不足、文件格式不支持等)。
内容的提问来源于stack exchange,提问作者Fred Kerber
相关产品推荐
相关产品推荐

