簡體   English   中英

如何在vb.net中使用HttpClient讀取JSON響應

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

我已經建立了一個用於訪問WEB API服務的Java例程,但是我在ASP.Net的VB等效版本中苦苦掙扎。 我得到了API響應,但是我不知道如何將其轉換為json元素。

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;
    }

但是在我的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

任何幫助表示贊賞。

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。 確保您有對JSON.NET的引用。 另外,在ASP.NET中使用.Result也是一個問題,很容易導致死鎖。 最好使用await

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM