List of usage examples for com.squareup.okhttp OkHttpClient setFollowRedirects
public void setFollowRedirects(boolean followRedirects)
From source file:at.bitfire.dav4android.DavResource.java
License:Open Source License
/** * Creates a new DavResource which represents a WebDAV resource at the given location. * @param log #{@link Logger} which will be used for logging, or null for default * @param httpClient #{@link OkHttpClient} to access this object * @param location location of the WebDAV resource */// ww w . j ava2 s .c o m public DavResource(Logger log, OkHttpClient httpClient, HttpUrl location) { this.log = log != null ? log : Constants.log; this.httpClient = httpClient; this.location = location; // Don't follow redirects (only useful for GET/POST). // This means we have to handle 30x responses manually. httpClient.setFollowRedirects(false); }
From source file:cn.finalteam.okhttpfinal.OkHttpFactory.java
License:Apache License
public static OkHttpClient getOkHttpClientFactory(long timeout) { OkHttpClient client = new OkHttpClient(); ///*from w ww .j a v a 2s. c om*/ client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS); client.setReadTimeout(timeout, TimeUnit.MILLISECONDS); //??? client.setRetryOnConnectionFailure(false); //??? client.setFollowRedirects(true); //?cookie client.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER)); return client; }
From source file:com.android.mms.service_alt.MmsHttpClient.java
License:Apache License
/** * Open an HTTP connection/*from w w w .ja v a2 s. co m*/ * * TODO: The following code is borrowed from android.net.Network.openConnection * Once that method supports proxy, we should use that instead * Also we should remove the associated HostResolver and ConnectionPool from * MmsNetworkManager * * @param url The URL to connect to * @param proxy The proxy to use * @return The opened HttpURLConnection * @throws MalformedURLException If URL is malformed */ private HttpURLConnection openConnection(URL url, final Proxy proxy) throws MalformedURLException { final String protocol = url.getProtocol(); OkHttpClient okHttpClient; if (protocol.equals("http")) { okHttpClient = new OkHttpClient(); okHttpClient.setFollowRedirects(false); okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); okHttpClient.setProxySelector(new ProxySelector() { @Override public List<Proxy> select(URI uri) { if (proxy != null) { return Arrays.asList(proxy); } else { return new ArrayList<Proxy>(); } } @Override public void connectFailed(URI uri, SocketAddress address, IOException failure) { } }); okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() { @Override public Request authenticate(Proxy proxy, Response response) throws IOException { return null; } @Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException { return null; } }); okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT)); okHttpClient.setConnectionPool(new ConnectionPool(3, 60000)); okHttpClient.setSocketFactory(SocketFactory.getDefault()); Internal.instance.setNetwork(okHttpClient, mHostResolver); if (proxy != null) { okHttpClient.setProxy(proxy); } return new HttpURLConnectionImpl(url, okHttpClient); } else if (protocol.equals("https")) { okHttpClient = new OkHttpClient(); okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier(); okHttpClient.setHostnameVerifier(verifier); okHttpClient.setSslSocketFactory(HttpsURLConnection.getDefaultSSLSocketFactory()); okHttpClient.setProxySelector(new ProxySelector() { @Override public List<Proxy> select(URI uri) { return Arrays.asList(proxy); } @Override public void connectFailed(URI uri, SocketAddress address, IOException failure) { } }); okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() { @Override public Request authenticate(Proxy proxy, Response response) throws IOException { return null; } @Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException { return null; } }); okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT)); okHttpClient.setConnectionPool(new ConnectionPool(3, 60000)); Internal.instance.setNetwork(okHttpClient, mHostResolver); return new HttpsURLConnectionImpl(url, okHttpClient); } else { throw new MalformedURLException("Invalid URL or unrecognized protocol " + protocol); } }
From source file:com.ayuget.redface.network.HTTPRedirection.java
License:Apache License
/** * Resolves a redirected URL {@code originalUrl} to its final location. * * If the URL is not really redirected, the original URL is returned. */// ww w. j a v a 2 s . com public static Observable<String> resolve(final String originalUrl) { return Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { OkHttpClient httpClient = new OkHttpClient(); httpClient.setFollowRedirects(false); Request request = new Request.Builder().url(originalUrl).build(); try { Response response = httpClient.newCall(request).execute(); if (response.code() == REDIRECTED_STATUS_CODE) { String locationHeader = response.header(LOCATION_HEADER); String targetUrl = locationHeader == null ? originalUrl : "http://" + new URL(originalUrl).getHost() + locationHeader; Timber.d("URL '%s' is redirected to '%s'", originalUrl, targetUrl); subscriber.onNext(targetUrl); } else { Timber.w("URL '%s' is not redirected", originalUrl); subscriber.onNext(originalUrl); } } catch (IOException e) { subscriber.onError(e); } } }); }
From source file:com.frostwire.http.HttpClient.java
License:Open Source License
private static OkHttpClient buildDefaultClient() { OkHttpClient c = new OkHttpClient(); c.setFollowRedirects(true); c.setFollowSslRedirects(true);/*w ww . j a v a2s.c o m*/ c.setConnectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); c.setReadTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); c.setWriteTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); c.setHostnameVerifier(buildHostnameVerifier()); c.setSslSocketFactory(buildSSLSocketFactory()); c.interceptors().add(new GzipInterceptor()); return c; }
From source file:com.groupon.odo.bmp.BrowserMobProxyHandler.java
License:Apache License
protected long proxyPlainTextRequest(final URL url, String pathInContext, String pathParams, HttpRequest request, final HttpResponse response) throws IOException { try {//w w w .jav a 2s . co m String urlStr = url.toString(); if (urlStr.toLowerCase().startsWith(Constants.ODO_INTERNAL_WEBAPP_URL)) { urlStr = "http://localhost:" + com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT) + "/odo"; } // setup okhttp to ignore ssl issues OkHttpClient okHttpClient = getUnsafeOkHttpClient(); okHttpClient.setFollowRedirects(false); okHttpClient.setFollowSslRedirects(false); Request.Builder okRequestBuilder = new Request.Builder(); /* * urlStr.indexOf(":") == urlStr.lastIndexOf(":") verifies that the url does not have a port * by checking it only has a : as part of http:// */ if (urlStr.startsWith("http://") && urlStr.indexOf(":") == urlStr.lastIndexOf(":")) { int httpPort = com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT); urlStr = urlStr.replace(getHostNameFromURL(urlStr), localIP + ":" + httpPort); } okRequestBuilder = okRequestBuilder.url(urlStr); // copy request headers Enumeration<?> enm = request.getFieldNames(); boolean isGet = "GET".equals(request.getMethod()); boolean hasContent = false; boolean usedContentLength = false; long contentLength = 0; while (enm.hasMoreElements()) { String hdr = (String) enm.nextElement(); if (!isGet && HttpFields.__ContentType.equals(hdr)) { hasContent = true; } if (!isGet && HttpFields.__ContentLength.equals(hdr)) { contentLength = Long.parseLong(request.getField(hdr)); usedContentLength = true; } Enumeration<?> vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) { hasContent = true; } if (!_DontProxyHeaders.containsKey(hdr)) { okRequestBuilder = okRequestBuilder.addHeader(hdr, val); //httpReq.addRequestHeader(hdr, val); } } } } if ("GET".equals(request.getMethod())) { // don't need to do anything else } else if ("POST".equals(request.getMethod()) || "PUT".equals(request.getMethod()) || "DELETE".equals(request.getMethod())) { RequestBody okRequestBody = null; if (hasContent) { final String contentType = request.getContentType(); final byte[] bytes = IOUtils.toByteArray(request.getInputStream()); okRequestBody = new RequestBody() { @Override public MediaType contentType() { MediaType.parse(contentType); return null; } @Override public void writeTo(BufferedSink bufferedSink) throws IOException { bufferedSink.write(bytes); } }; // we need to add some ODO specific headers to give ODO a hint for content-length vs transfer-encoding // since okHTTP will automatically chunk even if the request was not chunked // this allows Odo to set the appropriate headers when the server request is made if (usedContentLength) { okRequestBuilder = okRequestBuilder.addHeader("ODO-POST-TYPE", "content-length:" + contentLength); } } else { okRequestBody = RequestBody.create(null, new byte[0]); } if ("POST".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.post(okRequestBody); } else if ("PUT".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.put(okRequestBody); } else if ("DELETE".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.delete(okRequestBody); } } else if ("OPTIONS".equals(request.getMethod())) { // NOT SUPPORTED } else if ("HEAD".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.head(); } else { LOG.warn("Unexpected request method %s, giving up", request.getMethod()); request.setHandled(true); return -1; } Request okRequest = okRequestBuilder.build(); Response okResponse = okHttpClient.newCall(okRequest).execute(); // Set status and response message response.setStatus(okResponse.code()); response.setReason(okResponse.message()); // copy response headers for (int headerNum = 0; headerNum < okResponse.headers().size(); headerNum++) { String headerName = okResponse.headers().name(headerNum); if (!_DontProxyHeaders.containsKey(headerName) && !_ProxyAuthHeaders.containsKey(headerName)) { response.addField(headerName, okResponse.headers().value(headerNum)); } } // write output to response output stream try { IOUtils.copy(okResponse.body().byteStream(), response.getOutputStream()); } catch (Exception e) { // ignoring this until we refactor the proxy // The copy occasionally fails due to an issue where okResponse has more data in the body than it's supposed to // The client still gets all of the data it was expecting } request.setHandled(true); return okResponse.body().contentLength(); } catch (Exception e) { LOG.warn("Caught exception proxying: ", e); reportError(e, url, response); request.setHandled(true); return -1; } }
From source file:com.liferay.mobile.android.auth.CookieSignIn.java
License:Open Source License
protected Call signIn() throws Exception { if (!(session.getAuthentication() instanceof CookieAuthentication)) { throw new Exception("Can't sign in if authentication implementation is not " + "CookieAuthentication"); }//w ww. ja v a 2 s .c o m CookieAuthentication cookieAuthentication = getCookieAuthentication(session.getAuthentication()); username = cookieAuthentication.getUsername(); password = cookieAuthentication.getPassword(); cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); OkHttpClient client = new OkHttpClient(); Authenticator authenticator = authenticators.get(session.getServer()); if (authenticator != null) { client.setAuthenticator(authenticator); } client.setCookieHandler(cookieManager); client.setFollowRedirects(true); Builder builder = getBuilder(session, username, password); return client.newCall(builder.build()); }
From source file:com.liferay.mobile.android.http.client.OkHttpClientImpl.java
License:Open Source License
protected OkHttpClient getClient(int connectionTimeout) { OkHttpClient clone = client.clone(); clone.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); clone.setReadTimeout(connectionTimeout, TimeUnit.MILLISECONDS); clone.setWriteTimeout(connectionTimeout, TimeUnit.MILLISECONDS); clone.setFollowRedirects(false); return clone; }
From source file:com.liferay.mobile.sdk.auth.CookieSignIn.java
License:Open Source License
public static void signIn(Config config, CookieCallback callback) { try {/* ww w.j a va 2 s . co m*/ Authentication auth = config.auth(); if (!(auth instanceof BasicAuthentication)) { throw new Exception( "Can't sign in if authentication implementation is not " + "BasicAuthentication"); } OkHttpClient client = new OkHttpClient(); CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); client.setCookieHandler(cookieManager); client.setFollowRedirects(true); Builder builder = new Builder(); MediaType contentType = MediaType.parse("application/x-www-form-urlencoded"); builder.post(RequestBody.create(contentType, getBody((BasicAuthentication) auth))); builder.addHeader("Cookie", "COOKIE_SUPPORT=true;"); builder.url(getLoginURL(config.server())); Call call = client.newCall(builder.build()); call.enqueue(getCallback(callback, cookieManager)); } catch (Exception e) { callback.onFailure(e); } }
From source file:com.lobobrowser.LoboBrowser.java
License:Open Source License
/** * Initializes the global URLStreamHandlerFactory. * <p>//from w w w .j a v a 2 s.c om * This method is invoked by {@link #init(boolean, boolean)}. */ public static void initProtocols(final SSLSocketFactory sslSocketFactory) { // Configure URL protocol handlers final PlatformStreamHandlerFactory factory = PlatformStreamHandlerFactory.getInstance(); URL.setURLStreamHandlerFactory(factory); final OkHttpClient okHttpClient = new OkHttpClient(); final ArrayList<Protocol> protocolList = new ArrayList<>(2); protocolList.add(Protocol.HTTP_1_1); protocolList.add(Protocol.HTTP_2); okHttpClient.setProtocols(protocolList); okHttpClient.setConnectTimeout(100, TimeUnit.SECONDS); // HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory); okHttpClient.setSslSocketFactory(sslSocketFactory); okHttpClient.setFollowRedirects(false); okHttpClient.setFollowSslRedirects(false); factory.addFactory(new OkUrlFactory(okHttpClient)); factory.addFactory(new LocalStreamHandlerFactory()); }