1
0
mirror of https://github.com/owncloud/android-library.git synced 2025-06-07 16:06:08 +00:00

make OwnCloudClient extend the warpper HttpClient

This commit is contained in:
theScrabi 2018-06-27 14:25:41 +02:00 committed by davigonz
parent 75905b5f74
commit 6e4ded84d9
10 changed files with 196 additions and 374 deletions

View File

@ -25,6 +25,7 @@
package com.owncloud.android.lib.common;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountsException;
import android.content.Context;
@ -33,26 +34,23 @@ import android.net.Uri;
import com.owncloud.android.lib.common.authentication.OwnCloudCredentials;
import com.owncloud.android.lib.common.authentication.OwnCloudCredentialsFactory;
import com.owncloud.android.lib.common.authentication.OwnCloudCredentialsFactory.OwnCloudAnonymousCredentials;
import com.owncloud.android.lib.common.http.HttpClient;
import com.owncloud.android.lib.common.http.HttpConstants;
import com.owncloud.android.lib.common.http.methods.HttpBaseMethod;
import com.owncloud.android.lib.common.http.methods.nonwebdav.HttpMethod;
import com.owncloud.android.lib.common.network.RedirectionPath;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.status.OwnCloudVersion;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.params.HttpParams;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Cookie;
import okhttp3.Headers;
import okhttp3.HttpUrl;
public class OwnCloudClient extends HttpClient {
@ -90,53 +88,11 @@ public class OwnCloudClient extends HttpClient {
*/
private OwnCloudClientManager mOwnCloudClientManager = null;
/**
* When 'true', the method {@link #executeMethod(HttpMethod)} tries to silently refresh credentials
* if fails due to lack of authorization, if credentials support authorization refresh.
*/
private boolean mSilentRefreshOfAccountCredentials = true;
private String mRedirectedLocation;
private boolean mFollowRedirects;
/**
* Constructor
*/
// public OwnCloudClient(Uri baseUri, HttpConnectionManager connectionMgr) {
//
// super(connectionMgr);
//
// if (baseUri == null) {
// throw new IllegalArgumentException("Parameter 'baseUri' cannot be NULL");
// }
// mBaseUri = baseUri;
//
// mInstanceNumber = sIntanceCounter++;
// Log_OC.d(TAG + " #" + mInstanceNumber, "Creating OwnCloudClient");
//
// String userAgent = OwnCloudClientManagerFactory.getUserAgent();
// getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent);
// getParams().setParameter(
// PARAM_PROTOCOL_VERSION,
// HttpVersion.HTTP_1_1
// );
//
// getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
// getParams().setParameter(
// PARAM_SINGLE_COOKIE_HEADER, // to avoid problems with some web servers
// PARAM_SINGLE_COOKIE_HEADER_VALUE
// );
//
// applyProxySettings();
//
// clearCredentials();
// }
public OwnCloudClient(Uri baseUri, HttpConnectionManager connectionMgr) {
super(connectionMgr);
public OwnCloudClient(Uri baseUri) {
if (baseUri == null) {
throw new IllegalArgumentException("Parameter 'baseUri' cannot be NULL");
}
@ -157,25 +113,6 @@ public class OwnCloudClient extends HttpClient {
clearCredentials();
}
private void applyProxySettings() {
String proxyHost = System.getProperty("http.proxyHost");
String proxyPortSt = System.getProperty("http.proxyPort");
int proxyPort = 0;
try {
if (proxyPortSt != null && proxyPortSt.length() > 0) {
proxyPort = Integer.parseInt(proxyPortSt);
}
} catch (Exception e) {
Log_OC.w(TAG, "Proxy port could not be read, keeping default value " + proxyPort);
}
if (proxyHost != null && proxyHost.length() > 0) {
HostConfiguration hostCfg = getHostConfiguration();
hostCfg.setProxy(proxyHost, proxyPort);
Log_OC.d(TAG, "Proxy settings: " + proxyHost + ":" + proxyPort);
}
}
public void setCredentials(OwnCloudCredentials credentials) {
if (credentials != null) {
mCredentials = credentials;
@ -192,91 +129,6 @@ public class OwnCloudClient extends HttpClient {
mCredentials.applyTo(this);
}
/**
* Requests the received method with the received timeout (milliseconds).
*
* Executes the method through the inherited HttpClient.executedMethod(method).
*
* Sets the socket and connection timeouts only for the method received.
*
* The timeouts are both in milliseconds; 0 means 'infinite';
* < 0 means 'do not change the default'
*
* @param method HTTP method request.
* @param readTimeout Timeout to set for data reception
* @param connectionTimeout Timeout to set for connection establishment
*/
public int executeMethod(HttpMethodBase method, int readTimeout, int connectionTimeout) throws IOException {
int oldSoTimeout = getParams().getSoTimeout();
int oldConnectionTimeout = getHttpConnectionManager().getParams().getConnectionTimeout();
try {
if (readTimeout >= 0) {
method.getParams().setSoTimeout(readTimeout); // this should be enough...
getParams().setSoTimeout(readTimeout); // ... but HTTPS needs this
}
if (connectionTimeout >= 0) {
getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
}
return executeMethod(method);
} finally {
getParams().setSoTimeout(oldSoTimeout);
getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout);
}
}
/**
* Requests the received method.
*
* Executes the method through the inherited HttpClient.executedMethod(method).
*
* @param method HTTP method request.
*/
@Override
public int executeMethod(HttpMethod method) throws IOException {
boolean repeatWithFreshCredentials;
int repeatCounter = 0;
int status;
do {
// Update User Agent
HttpParams params = method.getParams();
String userAgent = OwnCloudClientManagerFactory.getUserAgent();
params.setParameter(HttpMethodParams.USER_AGENT, userAgent);
preventCrashDueToInvalidPort(method);
Log_OC.d(TAG + " #" + mInstanceNumber, "REQUEST " +
method.getName() + " " + method.getPath());
//logCookiesAtRequest(method.getRequestHeaders(), "before");
//logCookiesAtState("before");
method.setFollowRedirects(false);
status = super.executeMethod(method);
checkFirstRedirection(method);
// TODO
// if (mOkHttpClient.followRedirects()) {
// status = followRedirection(method).getLastStatus();
// }
repeatWithFreshCredentials = checkUnauthorizedAccess(status, repeatCounter);
if (repeatWithFreshCredentials) {
repeatCounter++;
}
} while (repeatWithFreshCredentials);
//logCookiesAtRequest(method.getRequestHeaders(), "after");
//logCookiesAtState("after");
//logSetCookiesAtResponse(method.getResponseHeaders());
return status;
}
public int executeHttpMethod (HttpBaseMethod method) throws Exception {
boolean repeatWithFreshCredentials;
@ -297,14 +149,11 @@ public class OwnCloudClient extends HttpClient {
}
private void checkFirstRedirection(HttpMethod method) {
Header[] httpHeaders = method.getResponseHeaders();
final String location = method.getResponseHeaders()
.get("location");
for (Header httpHeader : httpHeaders) {
if ("location".equals(httpHeader.getName().toLowerCase())) {
mRedirectedLocation = httpHeader.getValue();
break;
}
if(location != null && !location.isEmpty()) {
mRedirectedLocation = location;
}
}
@ -322,11 +171,10 @@ public class OwnCloudClient extends HttpClient {
*
* @param method HTTP method to run.
* @throws IllegalArgumentException If 'method' targets an invalid port in an HTTP URI.
* @throws URIException If the URI to the target server cannot be built.
*/
private void preventCrashDueToInvalidPort(HttpMethod method) throws URIException {
int port = method.getURI().getPort();
String scheme = method.getURI().getScheme().toLowerCase();
private void preventCrashDueToInvalidPort(HttpMethod method) {
final int port = method.getUrl().port();
String scheme = method.getUrl().scheme().toLowerCase();
if ("http".equals(scheme) && port > 0xFFFF) {
// < 0 is not tested because -1 is used when no port number is specified in the URL;
// no problem, the network library will convert that in the default HTTP port
@ -334,57 +182,52 @@ public class OwnCloudClient extends HttpClient {
}
}
public RedirectionPath followRedirection(HttpMethod method) throws IOException {
public RedirectionPath followRedirection(HttpMethod method) throws Exception {
int redirectionsCount = 0;
int status = method.getStatusCode();
RedirectionPath result = new RedirectionPath(status, MAX_REDIRECTIONS_COUNT);
while (redirectionsCount < MAX_REDIRECTIONS_COUNT &&
(status == HttpStatus.SC_MOVED_PERMANENTLY ||
status == HttpStatus.SC_MOVED_TEMPORARILY ||
status == HttpStatus.SC_TEMPORARY_REDIRECT)
(status == HttpConstants.HTTP_MOVED_PERMANENTLY ||
status == HttpConstants.HTTP_MOVED_TEMPORARILY ||
status == HttpConstants.HTTP_TEMPORARY_REDIRECT)
) {
Header location = method.getResponseHeader("Location");
if (location == null) {
location = method.getResponseHeader("location");
}
final String location = method.getResponseHeader("Location") != null
? method.getResponseHeader("Location")
: method.getResponseHeader("location");
if (location != null) {
String locationStr = location.getValue();
Log_OC.d(TAG + " #" + mInstanceNumber,
"Location to redirect: " + locationStr);
"Location to redirect: " + location);
result.addLocation(locationStr);
result.addLocation(location);
// Release the connection to avoid reach the max number of connections per host
// due to it will be set a different url
exhaustResponse(method.getResponseBodyAsStream());
method.releaseConnection();
exhaustResponse(method.getResponseAsStream());
method.setUrl(HttpUrl.parse(location));
final String destination = method.getRequestHeader("Destination") != null
? method.getRequestHeader("Destination")
: method.getRequestHeader("destination");
method.setURI(new URI(locationStr, true));
Header destination = method.getRequestHeader("Destination");
if (destination == null) {
destination = method.getRequestHeader("destination");
}
if (destination != null) {
int suffixIndex = locationStr.lastIndexOf(WEBDAV_PATH_4_0);
String redirectionBase = locationStr.substring(0, suffixIndex);
final int suffixIndex = location.lastIndexOf(WEBDAV_PATH_4_0);
final String redirectionBase = location.substring(0, suffixIndex);
String destinationStr = destination.getValue();
String destinationPath = destinationStr.substring(mBaseUri.toString().length());
String redirectedDestination = redirectionBase + destinationPath;
final String destinationPath = destination.substring(mBaseUri.toString().length());
final String redirectedDestination = redirectionBase + destinationPath;
destination.setValue(redirectedDestination);
method.setRequestHeader(destination);
method.setRequestHeader("destination", destination);
}
status = super.executeMethod(method);
status = executeHttpMethod(method);
result.addStatus(status);
redirectionsCount++;
} else {
Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
status = HttpStatus.SC_NOT_FOUND;
status = HttpConstants.HTTP_NOT_FOUND;
}
}
return result;
@ -408,19 +251,6 @@ public class OwnCloudClient extends HttpClient {
}
}
/**
* Sets the connection and wait-for-data timeouts to be applied by default to the methods
* performed by this client.
*/
public void setDefaultTimeouts(int defaultDataTimeout, int defaultConnectionTimeout) {
if (defaultDataTimeout >= 0) {
getParams().setSoTimeout(defaultDataTimeout);
}
if (defaultConnectionTimeout >= 0) {
getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout);
}
}
public Uri getOldFilesWebdavUri() {
return Uri.parse(mBaseUri + WEBDAV_PATH_4_0);
}
@ -459,81 +289,56 @@ public class OwnCloudClient extends HttpClient {
return mCredentials;
}
private void logCookiesAtRequest(Header[] headers, String when) {
private void logCookiesAtRequest(Headers headers, String when) {
int counter = 0;
for (int i = 0; i < headers.length; i++) {
if (headers[i].getName().toLowerCase().equals("cookie")) {
for (final String cookieHeader : headers.toMultimap().get("cookie")) {
Log_OC.d(TAG + " #" + mInstanceNumber,
"Cookies at request (" + when + ") (" + counter++ + "): " +
headers[i].getValue());
}
"Cookies at request (" + when + ") (" + counter++ + "): "
+ cookieHeader);
}
if (counter == 0) {
Log_OC.d(TAG + " #" + mInstanceNumber, "No cookie at request before");
}
}
private void logCookiesAtState(String string) {
Cookie[] cookies = getState().getCookies();
if (cookies.length == 0) {
Log_OC.d(TAG + " #" + mInstanceNumber, "No cookie at STATE before");
} else {
Log_OC.d(TAG + " #" + mInstanceNumber, "Cookies at STATE (before)");
for (int i = 0; i < cookies.length; i++) {
Log_OC.d(TAG + " #" + mInstanceNumber, " (" + i + "):" +
"\n name: " + cookies[i].getName() +
"\n value: " + cookies[i].getValue() +
"\n domain: " + cookies[i].getDomain() +
"\n path: " + cookies[i].getPath()
);
}
}
}
private void logSetCookiesAtResponse(Header[] headers) {
private void logSetCookiesAtResponse(Headers headers) {
int counter = 0;
for (int i = 0; i < headers.length; i++) {
if (headers[i].getName().toLowerCase().equals("set-cookie")) {
for (final String cookieHeader : headers.toMultimap().get("set-cookie")) {
Log_OC.d(TAG + " #" + mInstanceNumber,
"Set-Cookie (" + counter++ + "): " + headers[i].getValue());
}
"Set-Cookie (" + counter++ + "): " + cookieHeader);
}
if (counter == 0) {
Log_OC.d(TAG + " #" + mInstanceNumber, "No set-cookie");
}
}
public String getCookiesString() {
Cookie[] cookies = getState().getCookies();
String cookiesString = "";
for (Cookie cookie : cookies) {
cookiesString = cookiesString + cookie.toString() + ";";
public List<Cookie> getCookiesFromCurrentAccount() {
return getOkHttpClient().cookieJar().loadForRequest(HttpUrl.parse(
getAccount().getBaseUri().toString()));
}
// logCookie(cookie);
public String getCookiesString() {
String cookiesString = "";
for (Cookie cookie : getCookiesFromCurrentAccount()) {
cookiesString += cookie.toString() + ";";
}
return cookiesString;
}
public int getConnectionTimeout() {
return getHttpConnectionManager().getParams().getConnectionTimeout();
}
public int getDataTimeout() {
return getParams().getSoTimeout();
public void setCookiesForCurrentAccount(List<Cookie> cookies) {
getOkHttpClient().cookieJar().saveFromResponse(HttpUrl.parse(
getAccount().getBaseUri().toString()), cookies);
}
private void logCookie(Cookie cookie) {
Log_OC.d(TAG, "Cookie name: " + cookie.getName());
Log_OC.d(TAG, " value: " + cookie.getValue());
Log_OC.d(TAG, " domain: " + cookie.getDomain());
Log_OC.d(TAG, " path: " + cookie.getPath());
Log_OC.d(TAG, " version: " + cookie.getVersion());
Log_OC.d(TAG, " expiryDate: " +
(cookie.getExpiryDate() != null ? cookie.getExpiryDate().toString() : "--"));
Log_OC.d(TAG, " comment: " + cookie.getComment());
Log_OC.d(TAG, " secure: " + cookie.getSecure());
Log_OC.d(TAG, "Cookie name: " + cookie.name());
Log_OC.d(TAG, " value: " + cookie.value());
Log_OC.d(TAG, " domain: " + cookie.domain());
Log_OC.d(TAG, " path: " + cookie.path());
Log_OC.d(TAG, " expiryDate: " + cookie.expiresAt());
Log_OC.d(TAG, " secure: " + cookie.secure());
}
@ -545,10 +350,6 @@ public class OwnCloudClient extends HttpClient {
return mVersion;
}
public void setContext(Context context) {
this.mContext = context;
}
public Context getContext() {
return mContext;
}
@ -561,18 +362,6 @@ public class OwnCloudClient extends HttpClient {
return mAccount;
}
/**
* Enables or disables silent refresh of credentials, if supported by credentials themselves.
*/
public void setSilentRefreshOfAccountCredentials(boolean silentRefreshOfAccountCredentials) {
mSilentRefreshOfAccountCredentials = silentRefreshOfAccountCredentials;
}
public boolean getSilentRefreshOfAccountCredentials() {
return mSilentRefreshOfAccountCredentials;
}
/**
* Checks the status code of an execution and decides if should be repeated with fresh credentials.
*
@ -632,7 +421,7 @@ public class OwnCloudClient extends HttpClient {
*/
private boolean shouldInvalidateAccountCredentials(int httpStatusCode) {
boolean should = (httpStatusCode == HttpStatus.SC_UNAUTHORIZED || isIdPRedirection()); // invalid credentials
boolean should = (httpStatusCode == HttpConstants.HTTP_UNAUTHORIZED || isIdPRedirection()); // invalid credentials
should &= (mCredentials != null && // real credentials
!(mCredentials instanceof OwnCloudCredentialsFactory.OwnCloudAnonymousCredentials));

View File

@ -173,7 +173,7 @@ public class OwnCloudClientFactory {
" in the system will be used for HTTPS connections", e);
}
OwnCloudClient client = new OwnCloudClient(uri, NetworkUtils.getMultiThreadedConnManager());
OwnCloudClient client = new OwnCloudClient(uri);
client.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);

View File

@ -115,7 +115,6 @@ public class SingleSessionManager implements OwnCloudClientManager {
account.getBaseUri(),
context.getApplicationContext(),
true); // TODO remove dependency on OwnCloudClientFactory
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
client.setAccount(account);
client.setContext(context);
client.setOwnCloudClientManager(this);

View File

@ -26,8 +26,8 @@
package com.owncloud.android.lib.common.accounts;
import java.io.IOException;
import org.apache.commons.httpclient.Cookie;
import java.util.ArrayList;
import java.util.List;
import android.accounts.Account;
import android.accounts.AccountManager;
@ -43,6 +43,8 @@ import com.owncloud.android.lib.common.authentication.OwnCloudCredentialsFactory
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.status.OwnCloudVersion;
import okhttp3.Cookie;
public class AccountUtils {
private static final String TAG = AccountUtils.class.getSimpleName();
@ -217,7 +219,6 @@ public class AccountUtils {
}
/**
* Restore the client cookies persisted in an account stored in the system AccountManager.
*
@ -239,19 +240,18 @@ public class AccountUtils {
String cookiesString = am.getUserData(account, Constants.KEY_COOKIES);
if (cookiesString != null) {
String[] cookies = cookiesString.split(";");
if (cookies.length > 0) {
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = new Cookie();
int equalPos = cookies[i].indexOf('=');
cookie.setName(cookies[i].substring(0, equalPos));
cookie.setValue(cookies[i].substring(equalPos + 1));
cookie.setDomain(serverUri.getHost()); // VERY IMPORTANT
cookie.setPath(serverUri.getPath()); // VERY IMPORTANT
client.getState().addCookie(cookie);
}
String[] rawCookies = cookiesString.split(";");
List<Cookie> cookieList = new ArrayList<>(rawCookies.length);
for(String rawCookie : rawCookies) {
final int equalPos = rawCookie.indexOf('=');
cookieList.add(new Cookie.Builder()
.name(rawCookie.substring(0, equalPos))
.value(rawCookie.substring(equalPos + 1))
.domain(serverUri.getHost())
.path(serverUri.getPath())
.build());
}
client.setCookiesForCurrentAccount(cookieList);
}
}
}

View File

@ -82,12 +82,6 @@ public class OwnCloudBasicCredentials implements OwnCloudCredentials {
.addRequestInterceptor(
new BasicAuthInterceptor(mUsername, mPassword)
);
//TODO Update from here down
client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
client.getParams().setAuthenticationPreemptive(mAuthenticationPreemptive);
client.getParams().setCredentialCharset(OwnCloudCredentialsFactory.CREDENTIAL_CHARSET);
client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(mUsername, mPassword));
}
@Override

View File

@ -70,17 +70,6 @@ public class OwnCloudBearerCredentials implements OwnCloudCredentials {
HttpClient.getOkHttpInterceptor()
.addRequestInterceptor(new BarearAuthInterceptor(mAccessToken));
List<String> authPrefs = new ArrayList<>(1);
authPrefs.add(BearerAuthScheme.AUTH_POLICY);
client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
client.getParams().setAuthenticationPreemptive(true); // true enforces BASIC AUTH ; library is stupid
client.getParams().setCredentialCharset(OwnCloudCredentialsFactory.CREDENTIAL_CHARSET);
client.getState().setCredentials(
AuthScope.ANY,
new BearerCredentials(mAccessToken)
);
}
@Override

View File

@ -25,6 +25,13 @@
package com.owncloud.android.lib.common.authentication;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.http.HttpClient;
import com.owncloud.android.lib.common.http.interceptors.BarearAuthInterceptor;
import com.owncloud.android.lib.common.http.interceptors.BasicAuthInterceptor;
import com.owncloud.android.lib.common.http.interceptors.HttpInterceptor;
import com.owncloud.android.lib.common.http.interceptors.SamlAuthInterceptor;
import java.util.ArrayList;
public class OwnCloudCredentialsFactory {
@ -64,8 +71,16 @@ public class OwnCloudCredentialsFactory {
@Override
public void applyTo(OwnCloudClient client) {
client.getState().clearCredentials();
client.getState().clearCookies();
ArrayList<HttpInterceptor.RequestInterceptor> requestInterceptors = HttpClient.getOkHttpInterceptor().getRequestInterceptors();
// Clear previous basic credentials
for (HttpInterceptor.RequestInterceptor requestInterceptor : requestInterceptors) {
if (requestInterceptor instanceof BasicAuthInterceptor
|| requestInterceptor instanceof BarearAuthInterceptor
|| requestInterceptor instanceof SamlAuthInterceptor) {
requestInterceptors.remove(requestInterceptor);
}
}
}
@Override

View File

@ -50,10 +50,6 @@ public class OwnCloudSamlSsoCredentials implements OwnCloudCredentials {
@Override
public void applyTo(OwnCloudClient client) {
client.getParams().setAuthenticationPreemptive(false);
client.getParams().setCredentialCharset(OwnCloudCredentialsFactory.CREDENTIAL_CHARSET);
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
final ArrayList<HttpInterceptor.RequestInterceptor> requestInterceptors =
HttpClient.getOkHttpInterceptor().getRequestInterceptors();

View File

@ -25,6 +25,7 @@
package com.owncloud.android.lib.common.http;
import android.content.Context;
import java.util.concurrent.TimeUnit;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.owncloud.android.lib.BuildConfig;
@ -39,9 +40,7 @@ import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
import java.util.Arrays;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
@ -59,6 +58,10 @@ public class HttpClient {
private static HttpInterceptor sOkHttpInterceptor;
private static Context sContext;
public HttpClient() {
}
public static void setContext(Context context) {
sContext = context;
}
@ -99,4 +102,21 @@ public class HttpClient {
}
return sOkHttpInterceptor;
}
/**
* Sets the connection and wait-for-data timeouts to be applied by default to the methods
* performed by this client.
*/
public void setDefaultTimeouts(int defaultDataTimeout, int defaultConnectionTimeout) {
OkHttpClient.Builder clientBuilder = getOkHttpClient().newBuilder();
if (defaultDataTimeout >= 0) {
clientBuilder
.readTimeout(defaultDataTimeout, TimeUnit.MILLISECONDS)
.writeTimeout(defaultDataTimeout, TimeUnit.MILLISECONDS);
}
if (defaultConnectionTimeout >= 0) {
clientBuilder.connectTimeout(defaultConnectionTimeout, TimeUnit.MILLISECONDS);
}
sOkHttpClient = clientBuilder.build();
}
}

View File

@ -60,59 +60,19 @@ public abstract class HttpBaseMethod {
.build();
}
// Connection parameters
public void setReadTimeout(long readTimeout, TimeUnit timeUnit) {
mOkHttpClient = mOkHttpClient.newBuilder()
.readTimeout(readTimeout, timeUnit)
.build();
public void abort() {
mCall.cancel();
}
public void setConnectionTimeout(long connectionTimeout, TimeUnit timeUnit) {
mOkHttpClient = mOkHttpClient.newBuilder()
.readTimeout(connectionTimeout, timeUnit)
.build();
public boolean isAborted() {
return mCall.isCanceled();
}
public void setFollowRedirects(boolean followRedirects) {
mOkHttpClient = mOkHttpClient.newBuilder()
.followRedirects(followRedirects)
.build();
}
public void setRetryOnConnectionFailure(boolean retryOnConnectionFailure) {
mOkHttpClient = mOkHttpClient.newBuilder()
.retryOnConnectionFailure(retryOnConnectionFailure)
.build();
}
public boolean getRetryOnConnectionFailure() {
return mOkHttpClient.retryOnConnectionFailure();
}
// Request
public String getRequestHeader(String name) {
return mRequest.header(name);
}
public Headers getRequestHeaders() {
return mRequest.headers();
}
public void addRequestHeader(String name, String value) {
mRequest = mRequest.newBuilder()
.addHeader(name, value)
.build();
}
public void setRequestHeader(String name, String value) {
mRequest = mRequest.newBuilder()
.header(name, value)
.build();
}
public void setRequestBody(RequestBody requestBody) {
mRequestBody = requestBody;
}
//////////////////////////////
// Getter
//////////////////////////////
// Response
public int getStatusCode() {
@ -139,11 +99,71 @@ public abstract class HttpBaseMethod {
return mResponse.header(headerName);
}
public void abort() {
mCall.cancel();
public HttpUrl getUrl() {
return mRequest.url();
}
public boolean isAborted() {
return mCall.isCanceled();
public boolean getRetryOnConnectionFailure() {
return mOkHttpClient.retryOnConnectionFailure();
}
// Request
public String getRequestHeader(String name) {
return mRequest.header(name);
}
public Headers getRequestHeaders() {
return mRequest.headers();
}
//////////////////////////////
// Setter
//////////////////////////////
// Connection parameters
public void setReadTimeout(long readTimeout, TimeUnit timeUnit) {
mOkHttpClient = mOkHttpClient.newBuilder()
.readTimeout(readTimeout, timeUnit)
.build();
}
public void setConnectionTimeout(long connectionTimeout, TimeUnit timeUnit) {
mOkHttpClient = mOkHttpClient.newBuilder()
.readTimeout(connectionTimeout, timeUnit)
.build();
}
public void setFollowRedirects(boolean followRedirects) {
mOkHttpClient = mOkHttpClient.newBuilder()
.followRedirects(followRedirects)
.build();
}
public void setRetryOnConnectionFailure(boolean retryOnConnectionFailure) {
mOkHttpClient = mOkHttpClient.newBuilder()
.retryOnConnectionFailure(retryOnConnectionFailure)
.build();
}
public void addRequestHeader(String name, String value) {
mRequest = mRequest.newBuilder()
.addHeader(name, value)
.build();
}
public void setRequestHeader(String name, String value) {
mRequest = mRequest.newBuilder()
.header(name, value)
.build();
}
public void setRequestBody(RequestBody requestBody) {
mRequestBody = requestBody;
}
public void setUrl(HttpUrl url) {
mRequest = mRequest.newBuilder()
.url(url)
.build();
}
}