2017-09-05 134 views
0

我正在「舊」VB.Net應用程序中工作。我希望打電話給API,檢查我是否得到了404,解析JSON結果以及您可以使用API​​調用執行的所有其他常見事情。.NET Framework 4 VB.Net調用API

這樣做的最乾淨的方法是什麼?我以爲我可以使用HttpClient班,但我顯然不能! VS 2017不會讓我選擇將System.Net.Http作爲導入。

CODE

現在我這樣做,這似乎亂了。

Public Function GetUserInfo(ByVal authTokenBytes As Byte()) As WebPayWS.GetUserInfoResult 
    Dim token As New token 
    token.token1 = authTokenBytes 
    Dim userInformation As GetUserInfoResult = _myService.GetUserInfo(token) 
    If AccountExists(userInformation.accountno) Then 
    Dim response As String = GetAccountInfoFromApi(userInformation.accountno) 
    End If 
    Return userInformation 
End Function 

Private Function GetAccountInfoFromApi(accountno As String) As String 
    Dim accountInformationUrl As String = "URL" 
    Dim webClient As WebClient = New WebClient() 
    Return webClient.DownloadString(New Uri(accountInformationUrl)) 
End Function 

我堅持與WebClient?如果是,我如何使用WebClient檢查404

回答

1

您可以在異常與Web客戶端check this out

Private Function GetAccountInfoFromApi(accountno As String) As String 
Dim accountInformationUrl As String = "URL" 
Dim webClient As WebClient = New WebClient() 
'Return webClient.DownloadString(New Uri(accountInformationUrl)) 
Dim retString As String 

Try 
    retString = webClient.DownloadString(New Uri(accountInformationUrl)) 

    Catch ex As WebException 
    If ex.Status = WebExceptionStatus.ProtocolError AndAlso ex.Response IsNot Nothing Then 
     Dim resp = DirectCast(ex.Response, HttpWebResponse) 
     If resp.StatusCode = HttpStatusCode.NotFound Then 
      ' HTTP 404 
      'other steps you want here 
     End If 
    End If 
    'throw any other exception - this should not occur 
    Throw 
End Try 
Return retString 

End Function 
+0

所以確實如此,我不能在.NET Framework v4中使用HttpClient。謝謝@JimmySmith – Ciwan

+0

不,這是不正確的。 – djv

+0

是的,基於問題的第二部分 - 直到4.5之後才能使用HttpClient。但是如果你需要進一步研究,我推薦HttpWebRequest/Response類,https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(v=vs.71).aspx –

1

包裝它加入第一

  • 參考右鍵單擊項目
  • 添加...
    • 參考。 ..
  • 瀏覽
  • C:\ Program Files文件(x86)的\微軟ASP.NET \ ASP.NET MVC 4 \組件\ System.Net.Http.dll

enter image description here

現在,你可以導入

Imports System.Net.Http 

您還可以使用的NuGet,看到https://stackoverflow.com/a/13668810/832052

+0

hmm ,我認爲VS通常會自動執行此操作。我從來沒有這樣做,當在C#/框架工作4.5 – Ciwan

+0

看到這個[答案](https://stackoverflow.com/a/10308597/832052)太 – djv

+1

聽起來像我不能使用'httpClient.GetAsync url)'在.NET Framework 4中?我得到這個人一樣的錯誤https://stackoverflow.com/questions/35048217/await-requires-that-the-type-task-have-a-suitable-getawaiter-method – Ciwan