错误 401:未经授权将 json 数据发布到 URL

Error 401 Unauthorized in posting json data to a URL

提问人:LukaGer 提问时间:9/4/2023 更新时间:9/4/2023 访问量:53

问:

我必须将 json 发送到 url 以更新数据。 我使用了我在网络上找到的一些代码,我更改了它,但我从服务器中出错: 错误 401 未经授权。

这是我的代码:

      Dim jsonPost As New JsonPost("https://url/api/UpdateData")
      jsonPost.postData()

  Public Class JsonPost
    Private urlToPost As String = ""
    Public Sub New(ByVal urlToPost As String)
        Me.urlToPost = urlToPost
    End Sub
    Public Function postData() As Boolean
        Dim _user As String = "USER"
        Dim _password As String = "PASSWORD"

        Dim _json As String = ""
        _json = "{ ""Dato"":""AAA"""
        _json &= " "",""Comm"": [ "
        _json &= "{ ""Code"":""1"", ""Descr"":""Des1""} "
        _json &= "]}"

        ServicePointManager.SetTcpKeepAlive(True, 100000, 100000)
        ServicePointManager.Expect100Continue = True
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
        ServicePointManager.DefaultConnectionLimit = 100000000

        Dim webClient As New WebClient()
        Dim resByte As Byte()
        Dim resString As String
        Dim reqString() As Byte

        Try
            webClient.Credentials = New System.Net.NetworkCredential(_user, _password, "https://DOMAIN")
            reqString = System.Text.Encoding.Unicode.GetBytes(_json)
            webClient.Headers("content-type") = "application/json"
            reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(_json, Formatting.Indented))
            resByte = webClient.UploadData(Me.urlToPost, "post", reqString)
            resString = Encoding.Default.GetString(resByte)
            Console.WriteLine(resString)
            webClient.Dispose()
            Return True
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        Return False
    End Function

End Class

我可以检查什么? 谢谢

JSON vb.net WebClient

评论

0赞 Arvo 9/4/2023
回复“我使用了我在网络上找到的一些代码”——这通常会导致灾难。否则 - 您的凭据在 Postman 中使用时是否有效?
0赞 LukaGer 9/4/2023
我只使用凭据来访问网站,所以工作。我不知道其他方法可以尝试它们。
0赞 LukaGer 9/4/2023
邮差。。我不知道:-(
0赞 LukaGer 9/5/2023
我现在开始使用它了。如果我尝试获取数据,我的凭据会起作用。也许这是我在 vb 中的连接中的某个参数。
0赞 LukaGer 9/6/2023
我解决了将 webClient.Credentials = New System.Net.NetworkCredential(_user, _password, “DOMAIN”) 更改为 Dim bytes = Encoding.ASCII.GetBytes(m_userName + “:” + m_userPassword) Dim sauth = Convert.ToBase64String(bytes) 请求的问题。Headers.Add(“授权:基本” + sauth)

答: 暂无答案