如何在 vb.net 中使用 HttpClient 读取 JSON 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22777119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 17:16:08  来源:igfitidea点击:

How to read a JSON response using HttpClient in vb.net

vb.netasp.net-web-apidotnet-httpclient

提问by WaterBoy

I have built a java routine for accessing a WEB API service, however I am struggling with the VB equivalent for ASP.Net. I get the API response, but I don't know how to convert it to the json elements.

我已经构建了一个用于访问 WEB API 服务的 java 例程,但是我正在努力使用 ASP.Net 的 VB 等效项。我得到了 API 响应,但我不知道如何将其转换为 json 元素。

The java version is:

Java版本是:

    public boolean canLogin(){
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(hostURL + TOKEN_ACCESS_URL);
    httppost.addHeader("Accept", "application/json");

    // Add the post content
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
    nameValuePairs.add(new BasicNameValuePair("grant_type", "password"));
    nameValuePairs.add(new BasicNameValuePair("username", accessUserName));
    nameValuePairs.add(new BasicNameValuePair("password", accessPassword));
    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e1) {
        mobileLogDataHandler.ToLog(LogType.Error, "UnsupportedEncodingException closing data stream with error: " + e1.getLocalizedMessage() + ",detail:" + e1.getMessage() + " in canLogin", mResolver, RemoteDataHandler.class);
        return false;
    }

    // post the server
    InputStream inputStream = null;
    String result = null;
    try {
        HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode()!=200){
            mobileLogDataHandler.ToLog(LogType.Error, "Failed to get server token with error: " + response.getStatusLine().toString() + " in canLogin", mResolver, this.getClass());
            return false;
        }
        HttpEntity entity = response.getEntity();
        inputStream = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);// json is UTF-8 by default
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        result = sb.toString();
        inputStream.close();

    } catch (ClientProtocolException e) {
        mobileLogDataHandler.ToLog(LogType.Error, "ClientProtocolException trying to get bearer token from server with error: " + e.getLocalizedMessage() + ",detail:" + e.getMessage() + " in canLogin", mResolver, this.getClass());
        return false;
    } catch (IOException e) {
        mobileLogDataHandler.ToLog(LogType.Error, "IOException trying to get bearer token from server with error: " + e.getLocalizedMessage() + ",detail:" + e.getMessage() + " in canLogin", mResolver, this.getClass());
        return false;
    }

    //read the response content
    try{
        JSONObject jObject = new JSONObject(result);
        bearerToken =  jObject.getString("access_token");
        String expiryIntervalInSeconds = jObject.getString("expires_in");
        return canSaveNewBearerToken(bearerToken, expiryIntervalInSeconds);
    } catch (JSONException e){
        mobileLogDataHandler.ToLog(LogType.Error, "JSON error reading data sent from server for bearer token request with error: " + e.getLocalizedMessage() + ",detail:" + e.getMessage() + " in canLogin", mResolver, this.getClass());
        return false;
    }

But in my VB version - this is all I have. How can I read it so that I get the json objects out of it:

但是在我的 VB 版本中 - 这就是我所拥有的。我怎样才能读取它,以便从中获取 json 对象:

Public Function canLogin() As Boolean
    Dim client As HttpClient = New HttpClient
    client.DefaultRequestHeaders.Accept.Add(
            New System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"))

    'Dim content As HttpContent = New StringContent("grant_type=password&username=" & mAccessUserName & "&password=" & mAccessPassword)
    Dim urlEncodedList As New List(Of KeyValuePair(Of String, String))
    urlEncodedList.Add(New KeyValuePair(Of String, String)("grant_type", "password"))
    urlEncodedList.Add(New KeyValuePair(Of String, String)("username", mAccessUserName))
    urlEncodedList.Add(New KeyValuePair(Of String, String)("password", mAccessPassword))
    Dim content As New FormUrlEncodedContent(urlEncodedList)
    'content.Headers.ContentType = New Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded")  'not sure if i need this

    Dim response As HttpResponseMessage = client.PostAsync(New Uri(mHostURL & TOKEN_ACCESS_URL), content).Result

    If response.IsSuccessStatusCode Then
        Return True
    Else
        Return False
    End If


End Function

Any help appreciated.

任何帮助表示赞赏。

回答by Badri

Dim response As HttpResponseMessage = client.PostAsync(
                               New Uri("someuri"), content).Result

If response.IsSuccessStatusCode Then
    Dim json As String = response.Content.ReadAsStringAsync().Result
    Dim bearerToken As String = DirectCast(
               JObject.Parse(json).SelectToken("access_token"),
                                    String)
    Return True
Else
    Return False
End If

PS. Make sure you have a reference to JSON.NET. Also, using .Resultin ASP.NET is very problematic and can result easily in deadlocks. Better use await.

附注。确保您有对 JSON.NET 的引用。此外,.Result在 ASP.NET 中使用非常有问题,很容易导致死锁。更好地使用await