麻烦在VB.NET中使用httpwebrequest发布json [英] Trouble posting json using httpwebrequest in VB.NET

查看:176
本文介绍了麻烦在VB.NET中使用httpwebrequest发布json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个项目,通过vb.net观察程序将客户端的数据传输到Web服务。我没有为它编写Web端或API。我可以访问那些开发人员,但我坚持他们不熟悉的东西。我已经在jsonlint中测试了我的json并且它是完美的。我的连接代码也很好。我已经使用他们创建的测试API对其进行了测试。还有其他事情我不在了。当我运行他们的上传数据API时,我收到错误请求错误。没有细节。这就是它归还给我的。他们使用不同的前端成功测试了它们,但我正在vb.net中做我的工作。



编辑:我应该注意到,当我使用他们提供的API之一来提取他们系统的数据,这很好。我可以找回我需要的东西。在这种情况下,我不需要处理传递json块的行(与GetRequestStream相关的东西)。我一定是做错了。



编辑(2019-03-01):请注意,我发现我的代码有些变化,并尝试将其作为好吧,例如这里。还有其他类似的策略可以使用。我无法让这个策略发挥作用。我收到与发布该票的人相同的错误。



我尝试了什么:



这是我的代码:



I'm working on a project to get a client's data via a vb.net watcher program to a web service. I didn't write the web side or the API for it. I have access to those developers but I'm stuck on something they are not versed in. I've tested my json in jsonlint and it's perfect. My connection code is fine too. I've tested that using a test API they created. There's something else going on that I'm missing. I'm getting a "bad request" error when I run their upload data API. No details. That's all it's returning to me. They've successfully tested it on their end using a different front end but I'm doing my part in vb.net.

I should note that when I use one of the API's they provide to pull data OUT of their system, that works fine. I can retrieve what I need. In that case I don't need the lines that deal with passing the json block (the GetRequestStream related stuff). I must be doing something wrong with respect to that.

Edit (2019-03-01): Note that I had found some variations on my code and tried them as well, such as what's shown here. There are other similar strategies that claim to work. I could not get that strategy to work either. I'm getting the same error as the person who posted that ticket.

What I have tried:

Here's my code:

Dim hwReq As HttpWebRequest = Nothing
Dim hwResp As HttpWebResponse = Nothing

Try

    Dim noticeDataBodyContentBytes As Byte() = System.Text.Encoding.Unicode.GetBytes(noticeDataBodyContent)

    hwReq = HttpWebRequest.CreateHttp(webPortalURI)
    hwReq.Method = "POST"
    hwReq.ContentType = "application/json; charset=unicode"
    hwReq.ContentLength = noticeDataBodyContentBytes.Length
    hwReq.Accept = "application/json"
    hwReq.Headers.Add("timestamp", ts)
    hwReq.Headers.Add("apiclient", My.Settings.WebPortalClientID)
    hwReq.Headers.Add("apitoken", atkn)

    Dim noticeDataBodyContentStream As Stream = hwReq.GetRequestStream()
    noticeDataBodyContentStream.Write(noticeDataBodyContentBytes, 0, noticeDataBodyContentBytes.Length)
    noticeDataBodyContentStream.Close()

    hwResp = CType(hwReq.GetResponse, HttpWebResponse) '<<<<< error is here


Catch ex As Exception
    xfrmMain.memWatcherActivity.Text = "ERROR (" & DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") & "): " & friendlyErrorMessage & " - see log file for more info" & vbCrLf & xfrmMain.memWatcherActivity.Text
    errorMessageToLog = "ERROR: " & friendlyErrorMessage & " - " & ex.Message & vbCrLf & ex.StackTrace & vbCrLf & "(" & MethodBase.GetCurrentMethod().ReflectedType.FullName & ".vb." & MethodBase.GetCurrentMethod().Name & ")"
    Utilities.LogToFile(errorMessageToLog)
    If My.Settings.DevMode Then
        MessageBox.Show(errorMessageToLog, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    Else
        SendEmailMessage("ERROR: " & friendlyErrorMessage, errorMessageToLog, emergencyEmailPersonsArray)
    End If

Finally
    If hwResp IsNot Nothing Then
        hwResp.Close()
        hwResp.Dispose()
        hwResp = Nothing
    End If
    hwReq = Nothing

End Try





发生错误时我没有收到回复。它跳转到我的异常处理程序。



我的json块在noticeDataBodyContent变量中。就像我说的那样,我在jsonlint中测试了json并且它是完美的。



希望有人能让我知道我在这里做错了什么。



提前致谢!



基思



编辑(2019-03-01):我将我的策略改为HttpClient,我进一步了解了一下。而不是上述,我现在正在这样做:





I don't get a response when the error occurs. It jumps to my exception handler.

My json block is in the noticeDataBodyContent variable. Like I said, I tested the json in jsonlint and it's perfect.

Hoping someone can let me know what I'm doing wrong here.

Thanks in advance!

Keith

Edit (2019-03-01): I changed my strategy to HttpClient and I got a little further. Instead of the above, I'm doing this now:

Dim hc As New HttpClient
hc.DefaultRequestHeaders.Add("timestamp", ts)
hc.DefaultRequestHeaders.Add("apiclient", My.Settings.WebPortalClientID)
hc.DefaultRequestHeaders.Add("apitoken", atkn)
Dim u As New Uri(webPortalURI)
Dim sc As New StringContent(noticeDataBodyContent, Encoding.UTF8, "application/json")
Dim resp = hc.PostAsync(u, sc)
resp.Wait()





这就是我现在回来的:



{StatusCode:400,ReasonPhrase:'Bad Request',Version:1.1,Content :System.Net.Http.StreamContent,Headers:

{

Vary:Accept-Encoding

Vary:origin

变化:接受编码

缓存控制:无缓存

日期:星期五,2019年3月1日14:17:50 GMT

服务器:nginx / 1.15.8

内容长度:65

内容类型:application / json; charset = utf-8

}}



This is what I get back now:

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Vary: Accept-Encoding
Vary: origin
Vary: accept-encoding
Cache-Control: no-cache
Date: Fri, 01 Mar 2019 14:17:50 GMT
Server: nginx/1.15.8
Content-Length: 65
Content-Type: application/json; charset=utf-8
}}

推荐答案

在你完成之前,我认为你正在关闭流。

Looks to me you're closing the stream before you are finished with it.
noticeDataBodyContentStream.Close()

hwResp = CType(hwReq.GetResponse, HttpWebResponse) '<<<<< error is here


现在正在运行。我的所有代码都完全正确。唯一的问题是我应该在这里使用UTF8而不是用于json体的Unicode。他们在另一端的错误处理是不够的,无论我发送什么,如果它以某种方式坏,是坏请求,没有其他细节。这太荒谬了。



This is working now. Pretty much all my code was exactly right. The only issue was that I should have been using UTF8 here instead of Unicode for the json body. Their error handling on the other end is not sufficient and no matter what I send, if it's bad somehow, is "bad request" with no other details. It's ridiculous.

Dim noticeDataBodyContentBytes As Byte() = System.Text.Encoding.Unicode.GetBytes(noticeDataBodyContent)







Dim noticeDataBodyContentBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(noticeDataBodyContent)


这篇关于麻烦在VB.NET中使用httpwebrequest发布json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆