private void handleNon404s(RetrofitError e) { String msg = ""; if (e.getKind() == RetrofitError.Kind.NETWORK) { msg = String.format("Could not find the server %s", gitHubProperties.getBaseUrl()); } else if (e.getResponse().getStatus() == 401) { msg = "HTTP 401 Unauthorized."; } else if (e.getResponse().getStatus() == 403) { val rateHeaders = e.getResponse() .getHeaders() .stream() .filter(header -> RATE_LIMITING_HEADERS.contains(header.getName())) .map(Header::toString) .collect(Collectors.toList()); msg = "HTTP 403 Forbidden. Rate limit info: " + StringUtils.join(rateHeaders, ", "); } log.error(msg, e); }
static okhttp3.Request createRequest(Request request) { RequestBody requestBody; if (requiresRequestBody(request.getMethod()) && request.getBody() == null) { requestBody = RequestBody.create(null, NO_BODY); } else { requestBody = createRequestBody(request.getBody()); } okhttp3.Request.Builder builder = new okhttp3.Request.Builder() .url(request.getUrl()) .method(request.getMethod(), requestBody); List<Header> headers = request.getHeaders(); for (int i = 0, size = headers.size(); i < size; i++) { Header header = headers.get(i); String value = header.getValue(); if (value == null) { value = ""; } builder.addHeader(header.getName(), value); } return builder.build(); }
@Test public void responseNoContentType() throws IOException { okhttp3.Response okResponse = new okhttp3.Response.Builder() .code(200).message("OK") .body(new TestResponseBody("hello", null)) .addHeader("foo", "bar") .addHeader("kit", "kat") .protocol(Protocol.HTTP_1_1) .request(new okhttp3.Request.Builder() .url(HOST + "/foo/bar/") .get() .build()) .build(); Response response = Ok3Client.parseResponse(okResponse); assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/"); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getReason()).isEqualTo("OK"); assertThat(response.getHeaders()) // .containsExactly(new Header("foo", "bar"), new Header("kit", "kat")); TypedInput responseBody = response.getBody(); assertThat(responseBody.mimeType()).isNull(); assertThat(buffer(source(responseBody.in())).readUtf8()).isEqualTo("hello"); }
@Test public void emptyResponse() throws IOException { okhttp3.Response okResponse = new okhttp3.Response.Builder() .code(200) .message("OK") .body(new TestResponseBody("", null)) .addHeader("foo", "bar") .addHeader("kit", "kat") .protocol(Protocol.HTTP_1_1) .request(new okhttp3.Request.Builder() .url(HOST + "/foo/bar/") .get() .build()) .build(); Response response = Ok3Client.parseResponse(okResponse); assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/"); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getReason()).isEqualTo("OK"); assertThat(response.getHeaders()) // .containsExactly(new Header("foo", "bar"), new Header("kit", "kat")); assertThat(response.getBody()).isNull(); }
@Test public void get() throws InterruptedException, IOException { server.enqueue(new MockResponse() .addHeader("Hello", "World") .setBody("Hello!")); Response response = service.get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getReason()).isEqualTo("OK"); assertThat(response.getUrl()).isEqualTo(server.url("/").toString()); assertThat(response.getHeaders()).contains(new Header("Hello", "World")); assertThat(buffer(source(response.getBody().in())).readUtf8()).isEqualTo("Hello!"); RecordedRequest request = server.takeRequest(); assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getPath()).isEqualTo("/"); }
@Test public void post() throws IOException, InterruptedException { server.enqueue(new MockResponse() .addHeader("Hello", "World") .setBody("Hello!")); Response response = service.post(new TypedString("Hello?")); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getReason()).isEqualTo("OK"); assertThat(response.getUrl()).isEqualTo(server.url("/").toString()); assertThat(response.getHeaders()).contains(new Header("Hello", "World")); assertThat(buffer(source(response.getBody().in())).readUtf8()).isEqualTo("Hello!"); RecordedRequest request = server.takeRequest(); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getPath()).isEqualTo("/"); assertThat(request.getBody().readUtf8()).isEqualTo("Hello?"); }
@Test public void emptyBody() throws IOException, InterruptedException { server.enqueue(new MockResponse() .addHeader("Hello", "World") .setBody("Hello!")); Response response = service.post(); assertThat(response.getReason()).isEqualTo("OK"); assertThat(response.getUrl()).isEqualTo(server.url("/").toString()); assertThat(response.getHeaders()).contains(new Header("Hello", "World")); assertThat(buffer(source(response.getBody().in())).readUtf8()).isEqualTo("Hello!"); RecordedRequest request = server.takeRequest(); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getPath()).isEqualTo("/"); assertThat(request.getBody().readUtf8()).isEqualTo(""); }
@Override public void usersAndUploadedBy(@Query("cursor") String cursor, @Query("count") Integer count, Callback<Contacts> cb) { final Contacts data; if (cursor == null) { // First page: data = getContactsPages().get(""); } else { // Subsequent pages data = getContactsPages().get(cursor); } final Response response = new Response("/1.1/contacts/users_and_uploaded_by.json", 200, "ok", Collections.<Header>emptyList(), new TypedByteArray("application/json", new Gson().toJson(data).getBytes())); cb.success(data, response); }
public void testExecuteRequest_successAndMailRequestDisabled() throws Exception { final DigitsCallback callback = executeRequest(); final Response response = new Response(TWITTER_URL, HttpURLConnection.HTTP_ACCEPTED, "", new ArrayList<Header>(), null); final DigitsUser user = new DigitsUser(USER_ID, ""); callback.success(user, response); verify(digitsEventCollector).signupSuccess(digitsEventDetailsArgumentCaptor.capture()); final DigitsEventDetails digitsEventDetails = digitsEventDetailsArgumentCaptor.getValue(); assertNotNull(digitsEventDetails.elapsedTimeInMillis); assertEquals(sessionManager.isSet(), true); verify(sendButton).showFinish(); final ArgumentCaptor<Runnable> runnableArgumentCaptor = ArgumentCaptor.forClass (Runnable.class); verify(phoneEditText).postDelayed(runnableArgumentCaptor.capture(), eq(DigitsControllerImpl.POST_DELAY_MS)); final Runnable runnable = runnableArgumentCaptor.getValue(); runnable.run(); final ArgumentCaptor<Bundle> bundleArgumentCaptor = ArgumentCaptor.forClass(Bundle.class); verify(resultReceiver).send(eq(LoginResultReceiver.RESULT_OK), bundleArgumentCaptor.capture()); assertEquals(PHONE_WITH_COUNTRY_CODE, bundleArgumentCaptor.getValue().getString (DigitsClient.EXTRA_PHONE)); }
public void testExecuteRequest_successAndMailRequestEnabled() throws Exception { controller = new DummyConfirmationCodeController(resultReceiver, sendButton, resendButton, callMeButton, phoneEditText, PHONE_WITH_COUNTRY_CODE, sessionManager, digitsClient, errors, new ActivityClassManagerImp(), digitsEventCollector, true, timerTextView, digitsEventDetailsBuilder); final Response response = new Response(TWITTER_URL, HttpURLConnection.HTTP_OK, "", new ArrayList<Header>(), null); final DigitsUser user = new DigitsUser(USER_ID, ""); final DigitsCallback callback = executeRequest(); callback.success(user, response); verify(digitsEventCollector).signupSuccess(digitsEventDetailsArgumentCaptor.capture()); final DigitsEventDetails digitsEventDetails = digitsEventDetailsArgumentCaptor.getValue(); assertNotNull(digitsEventDetails.elapsedTimeInMillis); assertEquals(sessionManager.isSet(), true); verify(sendButton).showFinish(); verify(context).startActivityForResult(intentCaptor.capture(), eq(DigitsActivity.REQUEST_CODE)); final Intent intent = intentCaptor.getValue(); assertEquals(resultReceiver, intent.getParcelableExtra(DigitsClient.EXTRA_RESULT_RECEIVER)); assertEquals(PHONE_WITH_COUNTRY_CODE, intent.getStringExtra(DigitsClient.EXTRA_PHONE)); }
public void testExecuteRequest_failure() throws Exception { controller = new DummyConfirmationCodeController(resultReceiver, sendButton, resendButton, callMeButton, phoneEditText, PHONE_WITH_COUNTRY_CODE, sessionManager, digitsClient, errors, new ActivityClassManagerImp(), digitsEventCollector, true, timerTextView, digitsEventDetailsBuilder); final Response response = new Response(TWITTER_URL, HttpURLConnection.HTTP_OK, "", new ArrayList<Header>(), null); final DigitsUser user = new DigitsUser(USER_ID, ""); final DigitsCallback callback = executeRequest(); callback.failure(TestConstants.ANY_EXCEPTION); verify(callMeButton).showError(); verify(resendButton).showError(); verify(sendButton).showError(); }
@Test public void testCreate_user() throws Exception { final ArrayList<Header> headers = new ArrayList<>(); headers.add(new Header(ANY_HEADER, ANY_DATA)); headers.add(new Header(DigitsSession.TOKEN_HEADER, TestConstants.TOKEN)); headers.add(new Header(DigitsSession.SECRET_HEADER, TestConstants.SECRET)); final Response response = new Response(TestConstants.TWITTER_URL, HttpURLConnection.HTTP_ACCEPTED, "", headers, null); final DigitsUser user = new DigitsUser(TestConstants.USER_ID, DigitsSession.DEFAULT_PHONE_NUMBER); final DigitsSession session = DigitsSession.create(new Result<>(user, response), TestConstants.PHONE); final DigitsSession newSession = new DigitsSession(new TwitterAuthToken(TestConstants.TOKEN, TestConstants.SECRET), TestConstants.USER_ID, TestConstants.PHONE, DigitsSession.DEFAULT_EMAIL); assertEquals(session, newSession); }
private <E extends EntityType, T extends TokenType> void checkRefresh(final TokenProxy<E, T> tokenProxy, final Response response) { final List<Header> headers = response.getHeaders(); for(final Header header : headers) { if(TOKEN_HEADER_NAME.equals(header.getName())) { try { final AuthenticationToken.Json parsedHeader = objectMapper.readValue(header.getValue(), AuthenticationToken.Json.class); final AuthenticationToken<E, T> token = parsedHeader.buildToken(tokenProxy.getEntityType(), tokenProxy.getTokenType()); tokenRepository.update(tokenProxy, token); } catch (final IOException e) { throw new TokenRepositoryException(e); } break; } } }
private void postDashboard(Dashboard dashboard) throws APIException { try { Response response = mDhisApi.postDashboard(dashboard); // also, we will need to find UUID of newly created dashboard, // which is contained inside of HTTP Location header Header header = findLocationHeader(response.getHeaders()); // parse the value of header as URI and extract the id String dashboardId = Uri.parse(header.getValue()).getLastPathSegment(); // set UUID, change state and save dashboard dashboard.setUId(dashboardId); dashboard.setState(State.SYNCED); dashboard.save(); updateDashboardTimeStamp(dashboard); } catch (APIException apiException) { handleApiException(apiException); } }
@Override public void loadData(Callback<Object> callback) { if (!shouldFail) { callback.success(data, null); } else { RetrofitError error = null; switch (reason) { case NETWORK: error = RetrofitError.networkError("mock url", new IOException("Mock Network Exception")); break; case STATUS_CODE: error = RetrofitError.httpError("mock url", new Response("mock url", FailReason.httpcode, "Forbidden", new ArrayList<Header>(), null), null, null); break; case UNKNOWN: default: error = RetrofitError.unexpectedError("mock url", new Exception("Mock Exception")); break; } callback.failure(error); } }
public static int getNextPage(Response r) { List<Header> headers = r.getHeaders(); Map<String, String> headersMap = new HashMap<String, String>(headers.size()); for (Header header : headers) { headersMap.put(header.getName(), header.getValue()); } String link = headersMap.get("Link"); if (link != null) { String[] parts = link.split(","); try { PaginationLink bottomPaginationLink = new PaginationLink(parts[0]); if (bottomPaginationLink.rel == RelType.next) { return bottomPaginationLink.page; } } catch (Exception e) { e.printStackTrace(); } } return -1; }
public static Header getBasicAuthHeader() { // Add basic auth header if we have stored credentials if (Hawk.contains(Preferences.KEY_USERNAME) && Hawk.contains(Preferences.KEY_PASSWORD)) { // Get credentials from secure storage String username = Hawk.get(Preferences.KEY_USERNAME); String password = Hawk.get(Preferences.KEY_PASSWORD); // Create basic auth header String credentials = username + ":" + password; String header = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); // Add auth header in the request return new Header(AUTHORIZATION_HEADER, header); } return null; }
@Override public Response execute(Request request) throws IOException { try { List<Header> headers = new LinkedList<Header>(request.getHeaders()); // if logged in add auth header Optional<Account> account = loginManager.getAccount(); if (account.isPresent()) { String token = loginManager.getToken(account.get()); Header authHeader = new Header("Authorization", "Bearer " + token); headers.add(authHeader); } Request signedRequest = new Request( request.getMethod(), request.getUrl(), headers, request.getBody()); return super.execute(signedRequest); } catch (GoogleAuthException gae) { throw new IOException(gae); } }
@ExceptionHandler(RetrofitError.class) public void handleRetrofitError(RetrofitError e, HttpServletResponse response, HttpServletRequest request) throws IOException { if (e.getResponse() != null) { Map<String, Object> additionalContext = new HashMap<>(); additionalContext.put("url", e.getResponse().getUrl()); Header contentTypeHeader = e.getResponse().getHeaders() .stream() .filter(h -> h.getName().equalsIgnoreCase("content-type")) .findFirst() .orElse(null); if (contentTypeHeader != null && contentTypeHeader.getValue().toLowerCase().contains("application/json")) { // include any json responses additionalContext.put("body", CharStreams.toString( new InputStreamReader(e.getResponse().getBody().in(), Charsets.UTF_8) )); } storeException(request, response, new RetrofitErrorWrapper(e.getMessage(), additionalContext)); response.sendError(e.getResponse().getStatus(), e.getMessage()); } else { // no retrofit response (likely) indicates a NETWORK error handleException(e, response, request); } }
public static String getLocation(List<Header> headers){ for (Header header : headers) { if(null == header ){ continue; } if(null == header.getName()){ continue; } if(header.getName().isEmpty()){ continue; } if( null != header.getValue() && !header.getValue().isEmpty() ){ // add xwsse header to user if( header.getName().equals("Location") || header.getName().equals("Location")){ return header.getValue(); } } } return ""; }
public Response build(){ return new Response(url,status,reason,new ArrayList<Header>(),new TypedInput() { @Override public String mimeType() { return null; } @Override public long length() { return length; } @Override public InputStream in() throws IOException { return is; } }); }
/** * Parses a {@linkplain java.io.BufferedReader} into a {@linkplain retrofit.client.Response} object. * * @param url URL this mock response is answering for * @param input {@link java.io.BufferedReader} to read from * @return {@link retrofit.client.Response} object filled with data from the {@linkplain java.io.BufferedReader} * @throws IOException If an I/O error occurs while parsing */ public static Response parse(String url, BufferedReader input) throws IOException { Status status = status(input); List<Header> headers = headers(input); TypedInput body = body(contentType(headers), input); headers = new PlaceholderReplacer(headers) .withDate(new Date()) .withLength(body) .build(); return new Response( url, status.code(), status.reason(), headers, body ); }
public List<Header> build() { List<Header> result = new ArrayList<>(headers.size()); for (Header header : headers) { switch (header.getValue()) { case "${LENGTH}" : result.add(new Header(header.getName(), length)); break; case "${DATE}" : result.add(new Header(header.getName(), date)); break; default: result.add(header); } } return result; }
@Override public Response execute(Request request) throws IOException { List<Matcher<? super Request>> unmatchedRoutes = new LinkedList<>(); for (Route route : routes) { if (route.requestMatcher.matches(request)) return route.response.createFrom(request); unmatchedRoutes.add(route.requestMatcher); } StringDescription description = new StringDescription(); AnyOf.anyOf(unmatchedRoutes).describeTo(description); return new Response( request.getUrl(), 404, "No route matched", Collections.<Header>emptyList(), new TypedString("No matching route found. expected:\n" + description.toString()) ); }
@Test public void errorWithEmptyBodyDoesNotCrash() { TestClient client = new RestAdapter.Builder() .setEndpoint("http://example.com") .setClient(new Client() { @Override public Response execute(Request request) throws IOException { return new Response("", 400, "invalid request", Collections.<Header>emptyList(), null); } }) .setErrorHandler(errorHandler) .setExecutors(new SynchronousExecutor(), new SynchronousExecutor()) .build() .create(TestClient.class); try { client.getFullMenus(); failBecauseExceptionWasNotThrown(ApiException.class); } catch (ApiException e) { assertThat(e.getMessage()).isNull(); assertThat(e.getCause()).isNotNull(); } }
@Test public void UnauthorizedOnNonAuthRouteThrowsCorrectException() { TestClient client = new RestAdapter.Builder() .setEndpoint("http://example.com") .setClient(new Client() { @Override public Response execute(Request request) throws IOException { Error apiError = new Error("1234", "Invalid social credentials"); TypedInput input = new TypedByteArray("application/x-protobuf", apiError.toByteArray()); return new Response("", 401, "invalid request", Collections.<Header>emptyList(), input); } }) .setErrorHandler(errorHandler) .setExecutors(new SynchronousExecutor(), new SynchronousExecutor()) .setConverter(new WireConverter()) .build() .create(TestClient.class); try { client.getFullMenus(); failBecauseExceptionWasNotThrown(ExpiredSessionException.class); } catch (ExpiredSessionException e) { // No-op } }
@Test public void unauthorizedOnAuthRouteThrowsCorrectException() { AuthService service = new RestAdapter.Builder() .setEndpoint("http://example.com") .setClient(new Client() { @Override public Response execute(Request request) throws IOException { Error apiError = new Error("1234", "Invalid social credentials"); TypedInput input = new TypedByteArray("application/x-protobuf", apiError.toByteArray()); return new Response("", 401, "invalid request", Collections.<Header>emptyList(), input); } }) .setErrorHandler(errorHandler) .setExecutors(new SynchronousExecutor(), new SynchronousExecutor()) .setConverter(new WireConverter()) .build() .create(AuthService.class); try { service.getAuth(new AuthRequest()); failBecauseExceptionWasNotThrown(SocialCredentialsException.class); } catch (SocialCredentialsException e) { // No-op } }
public static HttpRequest prepareHttpRequest(final Request request) throws IOException { // Extract details from incoming request from Retrofit final String requestUrl = request.getUrl(); final String requestMethod = request.getMethod(); final List<Header> requestHeaders = request.getHeaders(); // URL and Method final HttpRequest httpRequest = new HttpRequest(requestUrl, requestMethod); // Headers for (Header header: requestHeaders) { httpRequest.header(header.getName(), header.getValue()); } return httpRequest; }
@Test public void testSendCustomHeader() throws Exception { // Given final String X_CUSTOM_AUTH = "X-Custom-Auth"; final String SOME_AUTH_TOKEN = "SOMEAUTHTOKEN"; HttpRequestClient httpRequestClient = new HttpRequestClient(); List<Header> customHeaders = ImmutableList.of(new Header(X_CUSTOM_AUTH, SOME_AUTH_TOKEN)); Request request = new Request("GET", HTTP_BIN_ROOT + "/get", customHeaders, null); // When final Response response = httpRequestClient.execute(request); ObjectMapper objectMapper = new ObjectMapper(); Map<String, Object> jsonObj = objectMapper.readValue(response.getBody().in(), Map.class); Map<String, Object> sentHeaders = (Map<String, Object>) jsonObj.get("headers"); // Then assertNotNull(response); assertThat(response.getStatus(), is(200)); assertThat(sentHeaders.get(X_CUSTOM_AUTH).toString(), is(SOME_AUTH_TOKEN)); }
@Test public void simpleHeaders() throws Exception { Request request = new Helper() // .setMethod("GET") // .setUrl("http://example.com") // .setPath("/foo/bar/") // .addHeader("ping", "pong") // .addHeader("kit", "kat") // .build(); assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getHeaders()) // .containsExactly(new Header("ping", "pong"), new Header("kit", "kat")); assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.getBody()).isNull(); }
@Test public void simpleInterceptorHeaders() throws Exception { Request request = new Helper() // .setMethod("GET") // .setUrl("http://example.com") // .setPath("/foo/bar/") // .addInterceptorHeader("ping", "pong") // .addInterceptorHeader("kit", "kat") // .build(); assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getHeaders()) // .containsExactly(new Header("ping", "pong"), new Header("kit", "kat")); assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.getBody()).isNull(); }
@Test public void headersAndInterceptorHeaders() throws Exception { Request request = new Helper() // .setMethod("GET") // .setUrl("http://example.com") // .setPath("/foo/bar/") // .addHeader("ping", "pong") // .addInterceptorHeader("kit", "kat") // .build(); assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getHeaders()) // .containsExactly(new Header("ping", "pong"), new Header("kit", "kat")); assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.getBody()).isNull(); }
@Test public void allThreeHeaderTypes() throws Exception { Request request = new Helper() // .setMethod("GET") // .setUrl("http://example.com") // .setPath("/foo/bar/") // .addHeader("ping", "pong") // .addInterceptorHeader("kit", "kat") // .addHeaderParam("fizz", "buzz") // .build(); assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getHeaders()).containsExactly(new Header("ping", "pong"), new Header("kit", "kat"), new Header("fizz", "buzz")); assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.getBody()).isNull(); }
@Test public void methodHeader() throws Exception { Request request = new Helper() // .setMethod("GET") // .setUrl("http://example.com") // .setPath("/foo/bar/") // .addHeader("ping", "pong") // .addHeaderParam("kit", "kat") // .build(); assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getHeaders()) // .containsExactly(new Header("ping", "pong"), new Header("kit", "kat")); assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.getBody()).isNull(); }
@Test public void headerParam() throws Exception { Request request = new Helper() // .setMethod("GET") // .setUrl("http://example.com") // .setPath("/foo/bar/") // .addHeader("ping", "pong") // .addHeaderParam("kit", "kat") // .build(); assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getHeaders()) // .containsExactly(new Header("ping", "pong"), new Header("kit", "kat")); assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/"); assertThat(request.getBody()).isNull(); }
/** * Return the number of seconds before the rate limit resets, or <code>-1</code> if the exception was not * the result of a HTTP 429 Too Many Requests rate limit error. * * @since 1.5 * @see #isRateLimitError * @return the number of seconds before the rate limit resets, or <code>-1</code> if the exception was not * the result of a HTTP 429 Too Many Requests rate limit error */ public long getRateLimitReset() { if (retrofitError.getResponse() == null) { return -1; } for (Header header : retrofitError.getResponse().getHeaders()) { if ("X-RateLimit-Reset".equals(header.getName())) { return Long.parseLong(header.getValue()); } } return -1; }
@Override public void intercept(RequestFacade request) { if (!loggedIn) { try { FormUrlEncodedTypedOutput to = new FormUrlEncodedTypedOutput(); to.addField("username", username); to.addField("password", password); to.addField("grant_type", "password"); String base64Auth = BaseEncoding.base64().encode(new String(clientId + ":" + clientSecret).getBytes()); List<Header> headers = new ArrayList<Header>(); headers.add(new Header("Authorization", "Basic " + base64Auth)); Request req = new Request("POST", tokenIssuingEndpoint, headers, to); Response resp = client.execute(req); if (resp.getStatus() < 200 || resp.getStatus() > 299) { throw new SecuredRestException("Login failure: " + resp.getStatus() + " - " + resp.getReason()); } else { String body = IOUtils.toString(resp.getBody().in()); accessToken = new Gson().fromJson(body, JsonObject.class).get("access_token").getAsString(); request.addHeader("Authorization", "Bearer " + accessToken); loggedIn = true; } } catch (Exception e) { throw new SecuredRestException(e); } } else { request.addHeader("Authorization", "Bearer " + accessToken); } }
private String getHeader(Response response, String key) { List<Header> headers = response.getHeaders(); for (Header header: headers) { if (key.equalsIgnoreCase(header.getName())) { return header.getValue(); } } return null; }
private static List<Header> createHeaders(Headers headers) { int size = headers.size(); List<Header> headerList = new ArrayList<>(size); for (int i = 0; i < size; i++) { headerList.add(new Header(headers.name(i), headers.value(i))); } return headerList; }