retrofit.client.Header Java Examples
The following examples show how to use
retrofit.client.Header.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Ok3Client.java From retrofit1-okhttp3-client with Apache License 2.0 | 6 votes |
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(); }
Example #2
Source File: GsonResponse.java From divide with Apache License 2.0 | 6 votes |
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; } }); }
Example #3
Source File: ApiUtils.java From GithubContributorsLib with Apache License 2.0 | 6 votes |
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; }
Example #4
Source File: Ok3ClientIntegrationTest.java From retrofit1-okhttp3-client with Apache License 2.0 | 6 votes |
@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(""); }
Example #5
Source File: Ok3ClientIntegrationTest.java From retrofit1-okhttp3-client with Apache License 2.0 | 6 votes |
@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?"); }
Example #6
Source File: Ok3ClientIntegrationTest.java From retrofit1-okhttp3-client with Apache License 2.0 | 6 votes |
@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("/"); }
Example #7
Source File: Ok3ClientTest.java From retrofit1-okhttp3-client with Apache License 2.0 | 6 votes |
@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(); }
Example #8
Source File: Ok3ClientTest.java From retrofit1-okhttp3-client with Apache License 2.0 | 6 votes |
@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"); }
Example #9
Source File: Ok3Client.java From retrofit1-okhttp3-client with Apache License 2.0 | 6 votes |
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(); }
Example #10
Source File: DashboardController.java From dhis2-android-dashboard with BSD 3-Clause "New" or "Revised" License | 6 votes |
private void postDashboard(Dashboard dashboard) throws APIException { try { Response 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); } }
Example #11
Source File: GithubTeamsUserRolesProvider.java From fiat with Apache License 2.0 | 6 votes |
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); }
Example #12
Source File: Ok3ClientIntegrationTest.java From retrofit1-okhttp3-client with Apache License 2.0 | 6 votes |
@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(""); }
Example #13
Source File: Ok3ClientIntegrationTest.java From retrofit1-okhttp3-client with Apache License 2.0 | 6 votes |
@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?"); }
Example #14
Source File: Ok3ClientIntegrationTest.java From retrofit1-okhttp3-client with Apache License 2.0 | 6 votes |
@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("/"); }
Example #15
Source File: Ok3ClientTest.java From retrofit1-okhttp3-client with Apache License 2.0 | 6 votes |
@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(); }
Example #16
Source File: Ok3ClientTest.java From retrofit1-okhttp3-client with Apache License 2.0 | 6 votes |
@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"); }
Example #17
Source File: MockRestAdapter.java From uphold-sdk-android with MIT License | 5 votes |
public MockRestAdapter(final String responseString, final HashMap<String, String> headers) { this.exceptionReference = new AtomicReference<>(); this.requestReference = new AtomicReference<>(); this.resultReference = new AtomicReference<>(); this.mockRestAdapter = new UpholdRestAdapter(); this.restAdapter = new RestAdapter.Builder().setEndpoint(BuildConfig.API_SERVER_URL) .setRequestInterceptor(this.mockRestAdapter.getUpholdRequestInterceptor()) .setClient(new Client() { @Override public Response execute(Request request) throws IOException { requestReference.set(request); return new Response("some/url", 200, "reason", new ArrayList<Header>() {{ if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); add(new retrofit.client.Header(key, value)); } } }}, new TypedByteArray("application/json", responseString == null ? new byte[0] : responseString.getBytes())); } }).build(); this.mockRestAdapter.setAdapter(this.restAdapter); }
Example #18
Source File: GsonResponse.java From divide with Apache License 2.0 | 5 votes |
public GsonResponse(String url, int status, String reason, List<Header> headers, Object o) { this.url = url; this.status = status; this.reason = reason; this.headers = headers; this.json = gson.toJson(o); try { is = IOUtils.toInputStream(json, "UTF-8"); length = json.length(); } catch (Exception e) { is = null; length = 0; } }
Example #19
Source File: GenericExceptionHandlers.java From kork with Apache License 2.0 | 5 votes |
@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); } }
Example #20
Source File: MoverAuthenticator.java From Mover with Apache License 2.0 | 5 votes |
@Override public Bundle getAuthToken(AccountManager manager, Account account) { if(!mSigning){ mPassword = manager.getPassword(account); } Bundle result = new Bundle(); try { Response response = mService.signIn(account.name, mPassword); if (isResponseSuccess(response)) { JSONObject json = asJson(asString(response)); if (json == null || json.has("errors") || json.has("error")) { result.putInt(KEY_ERROR_CODE, ERROR_CODE_INVALID_USER_DATA); return result; } for (Header header : response.getHeaders()) { if (isCookiesHeader(header)) { String cookies = header.getValue(); String token = findToken(HttpCookie.parse(cookies)); if (token != null) { result.putString(KEY_AUTHTOKEN, token); result.putString(USER_PICTURE_URL, findUserImage(mService.channel(account.name))); } } } } else { result.putInt(KEY_ERROR_CODE, ERROR_CODE_NETWORK_ERROR); } }catch (RetrofitError error){ result.putInt(KEY_ERROR_CODE, ERROR_CODE_NETWORK_ERROR); } return result; }
Example #21
Source File: RequestBuilder.java From android-discourse with Apache License 2.0 | 5 votes |
@Override public void addHeader(String name, String value) { if (name == null) { throw new IllegalArgumentException("Header name must not be null."); } headers.add(new Header(name, value)); }
Example #22
Source File: BaseService.java From tilt-game-android with MIT License | 5 votes |
protected Header getHeaderByName(List<Header> headers, String name) { for (Header header : headers) { if (!TextUtils.isEmpty(header.getName()) && header.getName().equals(name)) { return header; } } return null; }
Example #23
Source File: BaseService.java From tilt-game-android with MIT License | 5 votes |
protected void handleError(RetrofitError error, Intent intent, String broadcast) { if (!sAppIdInitialized) { throw new Error("Call setApplicationIdPrefix(BuildConfig.APPLICATION_ID) before handling errors"); } Response response = error.getResponse(); int status = (response == null) ? 0 : response.getStatus(); ApiErrorVO errorVO = null; if (response != null) { Header header = getHeaderByName(response.getHeaders(), "Content-Type"); if (header != null) { if (header.getValue().contains("application/json")) { try { errorVO = (ApiErrorVO) error.getBodyAs(ApiErrorVO.class); } catch (Exception exception) { exception.printStackTrace(); } } } } if (errorVO == null) { errorVO = new ApiErrorVO(); } errorVO.setErrorKind(error.getKind()); Intent broadcastIntent = new Intent(BROADCAST_ERROR); broadcastIntent.putExtra(KEY_ORIGINAL_ACTION, TextUtils.isEmpty(broadcast) ? intent.getAction() : broadcast); broadcastIntent.putExtra(KEY_API_ERROR_OBJECT, errorVO); broadcastIntent.putExtra(KEY_HTTP_STATUS, status); LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent); }
Example #24
Source File: RetrofitCurlClient.java From libcurldroid with Artistic License 2.0 | 5 votes |
private Response convertResult(Request request, Result result) throws IOException { Map<String, String> headerMap = result.getHeaders(); TypedInput input = new TypedByteArray(headerMap.get("Content-Type"), result.getDecodedBody()); List<Header> headers = new ArrayList<Header>(headerMap.size()); for (Entry<String, String> entry : headerMap.entrySet()) { headers.add(new Header(entry.getKey(), entry.getValue())); } return new Response(request.getUrl(), result.getStatus(), result.getStatusLine(), headers, input); }
Example #25
Source File: RetrofitCurlClient.java From libcurldroid with Artistic License 2.0 | 5 votes |
@Override public Response execute(Request request) throws IOException { List<Header> headers = request.getHeaders(); CurlHttp curlHttp = CurlHttp.newInstance(); if (callback != null) { callback.afterInit(curlHttp, request.getUrl()); } if (headers != null && headers.size() > 0) { for (Header header : headers) { Log.v(TAG, "add header: " + header.getName() + " " + header.getValue()); curlHttp.addHeader(header.getName(), header.getValue()); } } if ("get".equalsIgnoreCase(request.getMethod())) { // get curlHttp.getUrl(request.getUrl()); } else { // post TypedOutput body = request.getBody(); if (body != null) { Log.v(TAG, "set request body"); ByteArrayOutputStream os = new ByteArrayOutputStream((int) body.length()); body.writeTo(os); curlHttp.setBody(body.mimeType(), os.toByteArray()); } curlHttp.postUrl(request.getUrl()); } return convertResult(request, curlHttp.perform()); }
Example #26
Source File: Ok3Client.java From retrofit1-okhttp3-client with Apache License 2.0 | 5 votes |
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; }
Example #27
Source File: UpholdRetrofitErrorHandlingTest.java From uphold-sdk-android with MIT License | 5 votes |
public UpholdRetrofitErrorHandlingTest(Integer httpStatusCodeInput, List<Header> httpHeadersInput, String reason, Integer httpStatusCodeResponseExpected, Object expectedClass, String expectedReason) { this.httpStatusCodeInput = httpStatusCodeInput; this.httpHeadersInput = httpHeadersInput; this.reason = reason; this.httpStatusCodeResponseExpected = httpStatusCodeResponseExpected; this.expectedClass = expectedClass; this.expectedReason = expectedReason; }
Example #28
Source File: Ok3Client.java From retrofit1-okhttp3-client with Apache License 2.0 | 5 votes |
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; }
Example #29
Source File: UpholdRetrofitErrorHandlingTest.java From uphold-sdk-android with MIT License | 5 votes |
@Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { { 0, null, null, null, RuntimeException.class.getName(), "Invalid status code: 0" }, { 400, new ArrayList<Header>(), "reason", 400, BadRequestException.class.getName(), "400 reason" }, { 401, new ArrayList<Header>(), "reason", 401, AuthenticationRequiredException.class.getName(), "401 reason" }, { 404, new ArrayList<Header>(), "reason", 404, NotFoundException.class.getName(), String.format("Object or route not found: %s/v0/me", MOCK_URL) }, { 412, new ArrayList<Header>(), "reason", 412, BadRequestException.class.getName(), "Precondition failed" }, { 419, new ArrayList<Header>(), "reason", 419, BadRequestException.class.getName(), "Requested range not satisfiable" }, { 429, new ArrayList<Header>() {{ add(new Header("Retry-After", "10")); add(new Header("Rate-Limit-Total", "300")); }}, "reason", 429, ApiLimitExceedException.class.getName(), "You have exceeded Uphold's API rate limit of 300 requests. Current time window ends in 10 seconds." }, { 500, new ArrayList<Header>(), "reason", 500, RuntimeException.class.getName(), "500 reason" }}); }
Example #30
Source File: SnippetDetailFragment.java From Android-REST-API-Explorer with MIT License | 5 votes |
private void maybeDisplayResponseHeaders(Response response) { if (null != response.getHeaders()) { List<Header> headers = response.getHeaders(); String headerText = ""; for (Header header : headers) { headerText += header.getName() + " : " + header.getValue() + "\n"; } mResponseHeaders.setText(headerText); } }