List of usage examples for com.squareup.okhttp Response isRedirect
public boolean isRedirect()
From source file:at.bitfire.dav4android.DavResource.java
License:Open Source License
/** * Sends a GET request to the resource. Note that this method expects the server to * return an ETag (which is required for CalDAV and CardDAV, but not for WebDAV in general). * @param accept content of Accept header (must not be null, but may be */* ) * @return response body/* w w w . j a v a 2 s. com*/ * @throws DavException on WebDAV errors, or when the response doesn't contain an ETag */ public ResponseBody get(@NonNull String accept) throws IOException, HttpException, DavException { Response response = null; for (int attempt = 0; attempt < MAX_REDIRECTS; attempt++) { response = httpClient .newCall(new Request.Builder().get().url(location).header("Accept", accept).build()).execute(); if (response.isRedirect()) processRedirection(response); else break; } checkStatus(response); String eTag = response.header("ETag"); if (TextUtils.isEmpty(eTag)) // CalDAV servers MUST return ETag on GET [https://tools.ietf.org/html/rfc4791#section-5.3.4] // CardDAV servers MUST return ETag on GET [https://tools.ietf.org/html/rfc6352#section-6.3.2.3] throw new DavException("Received GET response without ETag"); properties.put(GetETag.NAME, new GetETag(eTag)); ResponseBody body = response.body(); if (body == null) throw new HttpException("GET without response body"); MediaType mimeType = body.contentType(); if (mimeType != null) properties.put(GetContentType.NAME, new GetContentType(mimeType)); return body; }
From source file:at.bitfire.dav4android.DavResource.java
License:Open Source License
/** * Sends a PUT request to the resource./*from w ww. ja v a 2 s.c o m*/ * @param body new resource body to upload * @param ifMatchETag value of "If-Match" header to set, or null to omit * @param ifNoneMatch indicates whether "If-None-Match: *" ("don't overwrite anything existing") header shall be sent * @return true if the request was redirected successfully, i.e. #{@link #location} and maybe resource name may have changed */ public boolean put(@NonNull RequestBody body, String ifMatchETag, boolean ifNoneMatch) throws IOException, HttpException { boolean redirected = false; Response response = null; for (int attempt = 0; attempt < MAX_REDIRECTS; attempt++) { Request.Builder builder = new Request.Builder().put(body).url(location); if (ifMatchETag != null) // only overwrite specific version builder.header("If-Match", StringUtils.asQuotedString(ifMatchETag)); if (ifNoneMatch) // don't overwrite anything existing builder.header("If-None-Match", "*"); response = httpClient.newCall(builder.build()).execute(); if (response.isRedirect()) { processRedirection(response); redirected = true; } else break; } checkStatus(response); String eTag = response.header("ETag"); if (TextUtils.isEmpty(eTag)) properties.remove(GetETag.NAME); else properties.put(GetETag.NAME, new GetETag(eTag)); return redirected; }
From source file:at.bitfire.dav4android.DavResource.java
License:Open Source License
/** * Sends a PROPFIND request to the resource. Expects and processes a 207 multi-status response. * #{@link #properties} are updated according to the multi-status response. * #{@link #members} is re-built according to the multi-status response (i.e. previous member entries won't be retained). * @param depth "Depth" header to send, e.g. 0 or 1 * @param reqProp properties to request *///from w ww.j ava2 s .co m public void propfind(int depth, Property.Name... reqProp) throws IOException, HttpException, DavException { // build XML request body XmlSerializer serializer = XmlUtils.newSerializer(); StringWriter writer = new StringWriter(); serializer.setOutput(writer); serializer.setPrefix("", XmlUtils.NS_WEBDAV); serializer.setPrefix("CAL", XmlUtils.NS_CALDAV); serializer.setPrefix("CARD", XmlUtils.NS_CARDDAV); serializer.startDocument("UTF-8", null); serializer.setPrefix("", XmlUtils.NS_WEBDAV); serializer.startTag(XmlUtils.NS_WEBDAV, "propfind"); serializer.startTag(XmlUtils.NS_WEBDAV, "prop"); for (Property.Name prop : reqProp) { serializer.startTag(prop.namespace, prop.name); serializer.endTag(prop.namespace, prop.name); } serializer.endTag(XmlUtils.NS_WEBDAV, "prop"); serializer.endTag(XmlUtils.NS_WEBDAV, "propfind"); serializer.endDocument(); // redirects must not followed automatically (as it may rewrite PROPFIND requests to GET requests) httpClient.setFollowRedirects(false); Response response = null; for (int attempt = 0; attempt < MAX_REDIRECTS; attempt++) { response = httpClient.newCall(new Request.Builder().url(location) .method("PROPFIND", RequestBody.create(MIME_XML, writer.toString())) .header("Depth", String.valueOf(depth)).build()).execute(); if (response.isRedirect()) processRedirection(response); else break; } checkStatus(response); assertMultiStatus(response); if (depth > 0) // collection listing requested, drop old member information members.clear(); @Cleanup Reader reader = response.body().charStream(); processMultiStatus(reader); }
From source file:com.digi.wva.internal.HttpClient.java
License:Mozilla Public License
/** * Log information of OkHttp Response objects * * <p>This method is protected, rather than private, due to a bug between JaCoCo and * the Android build tools which causes the instrumented bytecode to be invalid when this * method is private:// w w w . j a v a 2 s.c o m * <a href="http://stackoverflow.com/questions/17603192/dalvik-transformation-using-wrong-invoke-opcode" target="_blank">see StackOverflow question.</a> * </p> * @param response the HTTP response object to log */ protected void logResponse(Response response) { if (!doLogging) { // Logging is disabled - do nothing. return; } Request request = response.request(); StringBuilder log = new StringBuilder(); log.append( // e.g. <-- 200 GET /ws/hw/leds/foo String.format("\u2190 %d %s %s", response.code(), request.method(), request.urlString())); // Add on lines tracking any redirects that occurred. Response prior = response.priorResponse(); if (prior != null) { // Call out that there were prior responses. log.append(" (prior responses below)"); // Add a line to the log message for each prior response. // (For most if not all responses, there will likely be just one.) do { log.append(String.format("\n... prior response: %d %s %s", prior.code(), prior.request().method(), prior.request().urlString())); // If this is a redirect, log the URL we're being redirected to. if (prior.isRedirect()) { log.append(", redirecting to "); log.append(prior.header("Location", "[no Location header found?!]")); } prior = prior.priorResponse(); } while (prior != null); } Log.i(TAG, log.toString()); }
From source file:com.ibm.mobilefirstplatform.clientsdk.android.core.api.Request.java
License:Apache License
@Override protected Callback getCallback(final ResponseListener listener) { final RequestBody requestBody = savedRequestBody; final Request request = this; final Context ctx = this.context; return new Callback() { @Override/*from www . j a v a2 s . c om*/ public void onFailure(com.squareup.okhttp.Request request, IOException e) { if (listener != null) { listener.onFailure(null, e, null); } } @Override public void onResponse(com.squareup.okhttp.Response response) throws IOException { if (listener == null) { return; } AuthorizationManager authorizationManager = BMSClient.getInstance().getAuthorizationManager(); int responseCode = response.code(); Map<String, List<String>> responseHeaders = response.headers().toMultimap(); boolean isAuthorizationRequired = authorizationManager.isAuthorizationRequired(responseCode, responseHeaders); if (isAuthorizationRequired) { if (oauthFailCounter++ < 2) { authorizationManager.obtainAuthorization(ctx, new ResponseListener() { @Override public void onSuccess(Response response) { // this will take the auth hader that has been cached by obtainAuthorizationHeader request.sendRequest(listener, requestBody); } @Override public void onFailure(Response response, Throwable t, JSONObject extendedInfo) { listener.onFailure(response, t, extendedInfo); } }); } else { listener.onFailure(new ResponseImpl(response), null, null); } } else { if (response.isSuccessful() || response.isRedirect()) { listener.onSuccess(new ResponseImpl(response)); } else { listener.onFailure(new ResponseImpl(response), null, null); } } } }; }
From source file:com.ibm.mobilefirstplatform.clientsdk.android.core.internal.BaseRequest.java
License:Apache License
protected Callback getCallback(final ResponseListener listener) { return new Callback() { @Override/* www . j a v a2 s.c om*/ public void onFailure(Request request, IOException e) { listener.onFailure(null, e, null); } @Override public void onResponse(com.squareup.okhttp.Response response) throws IOException { if (response.isSuccessful() || response.isRedirect()) { listener.onSuccess(new ResponseImpl(response)); } else { listener.onFailure(new ResponseImpl(response), null, null); } } }; }
From source file:com.uber.sdk.rides.client.internal.RetrofitUberRidesClient.java
License:Open Source License
/** * Builds a RestAdapter.// ww w .ja v a 2 s. c o m */ private static RestAdapter buildRestAdapter(final Session session, String endpointHost, final OAuth2Helper oAuth2Helper, RestAdapter.LogLevel logLevel, OkHttpClient httpClient) throws IOException { RequestInterceptor requestInterceptor = new RequestInterceptor() { @Override public void intercept(RequestFacade requestFacade) { Credential credential = session.getCredential(); if (credential != null) { oAuth2Helper.refreshCredentialIfNeeded(credential); requestFacade.addHeader("Authorization", "Bearer " + credential.getAccessToken()); } else { requestFacade.addHeader("Authorization", "Token " + session.getServerToken()); } if (session.getLocale() != null) { requestFacade.addHeader("Accept-Language", session.getLocale().getLanguage()); } requestFacade.addHeader("X-Uber-User-Agent", "Java Rides SDK v" + LIB_VERSION); } }; if (httpClient == null) { httpClient = new OkHttpClient(); httpClient.setConnectTimeout(1, TimeUnit.MINUTES); httpClient.setReadTimeout(1, TimeUnit.MINUTES); httpClient.setFollowRedirects(false); httpClient.interceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request oldRequest = chain.request(); Response response = chain.proceed(oldRequest); if (response.isRedirect()) { String redirectUrl = response.header(HttpHeaders.LOCATION); Request newRequest = oldRequest.newBuilder().url(redirectUrl).build(); return chain.proceed(newRequest); } return response; } }); } return new RestAdapter.Builder().setEndpoint(endpointHost) .setConverter(new GsonConverter(new GsonBuilder().create())) .setRequestInterceptor(requestInterceptor).setClient(new OkClient(httpClient)).setLogLevel(logLevel) .build(); }
From source file:org.mariotaku.twidere.util.OAuthPasswordAuthenticator.java
License:Open Source License
public OAuthPasswordAuthenticator(final TwitterOAuth oauth, final LoginVerificationCallback loginVerificationCallback, final String userAgent) { final RestClient restClient = RestAPIFactory.getRestClient(oauth); this.oauth = oauth; this.client = (OkHttpRestClient) restClient.getRestClient(); final OkHttpClient okhttp = client.getClient(); okhttp.setCookieHandler(new CookieManager()); okhttp.networkInterceptors().add(new Interceptor() { @Override/*from w ww.j a v a 2 s . co m*/ public Response intercept(Chain chain) throws IOException { final Response response = chain.proceed(chain.request()); if (!response.isRedirect()) { return response; } final String location = response.header("Location"); final Response.Builder builder = response.newBuilder(); if (!TextUtils.isEmpty(location) && !endpoint.checkEndpoint(location)) { final HttpUrl originalLocation = HttpUrl .get(URI.create("https://api.twitter.com/").resolve(location)); final HttpUrl.Builder locationBuilder = HttpUrl.parse(endpoint.getUrl()).newBuilder(); for (String pathSegments : originalLocation.pathSegments()) { locationBuilder.addPathSegment(pathSegments); } for (int i = 0, j = originalLocation.querySize(); i < j; i++) { final String name = originalLocation.queryParameterName(i); final String value = originalLocation.queryParameterValue(i); locationBuilder.addQueryParameter(name, value); } final String encodedFragment = originalLocation.encodedFragment(); if (encodedFragment != null) { locationBuilder.encodedFragment(encodedFragment); } final HttpUrl newLocation = locationBuilder.build(); builder.header("Location", newLocation.toString()); } return builder.build(); } }); this.endpoint = restClient.getEndpoint(); this.loginVerificationCallback = loginVerificationCallback; this.userAgent = userAgent; }
From source file:quickbeer.android.next.network.utils.LoginRedirectInterceptor.java
License:Open Source License
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = chain.proceed(request); if (request.uri().getPath().equals("/Signin_r.asp") && response.isRedirect()) { Log.d(TAG, "Modifying response for login request"); return new Response.Builder().request(request).protocol(response.protocol()).code(200) .message(response.message()).handshake(response.handshake()).headers(response.headers()) .body(response.body()).networkResponse(response.networkResponse()).build(); }//from w w w .java2s . co m return response; }