2015-02-05 196 views
1

我需要通過發送Json請求連接到服務器。Asp.net Json Post請求

服務器的管理員告訴我應該安裝https服務器。

我買了一個ssl並安裝在我的服務器上。

他們給我發送了json字符串格式,即如何從他們的服務器獲取數據。 我試圖做出了榜樣請求,但每次我收到此錯誤:

The remote server returned an error: (400) Bad Request.

我打電話給他們,他們說,請求缺少私人或公共密鑰證書(我給他們的證書,他們安裝了它在他們的服務器上),但仍然得到相同的錯誤。

這是我使用的代碼:

誰能告訴我,如果我有什麼不對嗎?

Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click 
    POST("https://gw.bisan.com/api/apdemo_6", "{""user"":""MyUser"",""password"":""MyPASS"",""command"":""table"",""table"":""currency"",""fields"":[""symbol"",""rate""]}") 
    ' Read() 
End Sub 

Private Sub POST(url As String, jsonContent As String) 
    Try 
     Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest) 
     request.ContentType = "text/json" 
     request.Method = "POST" 
     Dim streamWriter As StreamWriter = New StreamWriter(request.GetRequestStream()) 
     streamWriter.Write(jsonContent) 
     streamWriter.Flush() 
     streamWriter.Close() 
     Dim httpResponse As HttpWebResponse = request.GetResponse() 
     Dim streamReader As StreamReader = New StreamReader(httpResponse.GetResponseStream()) 
     Dim result = streamReader.ReadToEnd() 
     Label1.Text = result.ToString 
    Catch ex As WebException 
     Label1.Text = ex.Message 
    End Try 
End Sub 
+0

您需要查看帖子請求(使用fiddler或其他工具),並與其預期帖子進行比較。 – Win 2015-02-05 18:17:56

+0

你可以解釋更多的PLZ – 2015-02-05 20:48:53

回答

1

開發機器http://www.telerik.com/fiddler上安裝小提琴手,啓動它,使您的機器發佈請求。 Fiddler將捕獲所有的發佈請求信息併爲您組織,以便您可以準確查看代碼發送的內容並將其與服務器期望的內容進行比較。從那裏你應該能夠更清楚地看到400錯誤原因並相應地修改你的代碼。

我猜想問題在於JSON字符串或request.ContentType =「text/json」的最終輸出(可能需要是application/json)。無論哪種方式,提琴手都是一個更快的找出方式。

0
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click 
    POST("https://gw.bisan.com/api/apdemo_6", "{""user"":""MyUser"",""password"":""MyPASS"",""command"":""table"",""table"":""currency"",""fields"":[""symbol"",""rate""]}") 
    ' Read() 
End Sub 

Private Sub POST(url As String, jsonContent As String) 
    Try 
     Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest) 
     request.ContentType = "application/json" 
     request.Method = "POST" 
     Dim streamWriter As StreamWriter = New StreamWriter(request.GetRequestStream()) 
     streamWriter.Write(jsonContent) 
     streamWriter.Flush() 
     streamWriter.Close() 
     Dim httpResponse As HttpWebResponse = request.GetResponse() 
     Dim streamReader As StreamReader = New StreamReader(httpResponse.GetResponseStream()) 
     Dim result = streamReader.ReadToEnd() 
     Label1.Text = result.ToString 
    Catch ex As WebException 
     Label1.Text = ex.Message 
    End Try 
End Sub