private OAuth2Token parseResponse(InputStream inputStream) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int n; while ((n = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, n); } inputStream.close(); return OAuth2Token.fromJSON(bos.toString("UTF-8")); }
public static OAuth2Token fromJSON(String string) throws IOException { try { Object value = new JSONTokener(string).nextValue(); if (value instanceof JSONObject) { return fromJSON((JSONObject) value); } else { throw new IOException("Invalid JSON data: "+value); } } catch (JSONException e) { Log.w(TAG, "JSON parse error", e); throw new IOException("Error parsing data: "+e.getMessage()); } }
@Test public void testFromJSONWithMissingFields() throws Exception { final String response = "{\n" + " \"access_token\":\"1/fFAGRNJru1FTz70BzhT3Zg\"\n" + "}"; final OAuth2Token token = OAuth2Token.fromJSON(response); assertThat(token.accessToken).isEqualTo("1/fFAGRNJru1FTz70BzhT3Zg"); assertThat(token.tokenType).isNull(); assertThat(token.refreshToken).isNull(); assertThat(token.expiresIn).isEqualTo(-1); }
@Test public void testFromJSONWithoutRefreshToken() throws Exception { final String response = "{\n" + " \"access_token\":\"1/fFAGRNJru1FTz70BzhT3Zg\",\n" + " \"expires_in\":3920,\n" + " \"token_type\":\"Bearer\"\n" + "}"; final OAuth2Token token = OAuth2Token.fromJSON(response); assertThat(token.accessToken).isEqualTo("1/fFAGRNJru1FTz70BzhT3Zg"); assertThat(token.tokenType).isEqualTo("Bearer"); assertThat(token.refreshToken).isNull(); assertThat(token.expiresIn).isEqualTo(3920); }
@Test public void testFromJSON() throws Exception { final String response = "{\n" + " \"access_token\":\"1/fFAGRNJru1FTz70BzhT3Zg\",\n" + " \"expires_in\":3920,\n" + " \"token_type\":\"Bearer\",\n" + " \"refresh_token\":\"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI\"\n" + "}"; final OAuth2Token token = OAuth2Token.fromJSON(response); assertThat(token.accessToken).isEqualTo("1/fFAGRNJru1FTz70BzhT3Zg"); assertThat(token.tokenType).isEqualTo("Bearer"); assertThat(token.refreshToken).isEqualTo("1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"); assertThat(token.expiresIn).isEqualTo(3920); }