Skip to content

If wifi isn't connected skips the setupAndroidProxy() method (issue 289) #333

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions AndroidAsync/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.koushikdutta.async"
android:versionCode="212"
android:versionName="2.1.2">
android:versionCode="213"
android:versionName="2.1.3">

<uses-permission android:name="android.permission.INTERNET"/>

Expand Down
108 changes: 67 additions & 41 deletions AndroidAsync/src/com/koushikdutta/async/http/AsyncHttpClient.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package com.koushikdutta.async.http;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.koushikdutta.async.AsyncSSLException;
import com.koushikdutta.async.AsyncServer;
Expand All @@ -26,6 +30,8 @@
import com.koushikdutta.async.parser.JSONObjectParser;
import com.koushikdutta.async.parser.StringParser;
import com.koushikdutta.async.stream.OutputStreamDataCallback;
import com.koushikdutta.async.util.ContextProvider;
import com.koushikdutta.async.util.NoContextException;

import org.json.JSONArray;
import org.json.JSONObject;
Expand All @@ -49,6 +55,7 @@

public class AsyncHttpClient {
private static AsyncHttpClient mDefaultInstance;

public static AsyncHttpClient getDefaultInstance() {
if (mDefaultInstance == null)
mDefaultInstance = new AsyncHttpClient(AsyncServer.getDefault());
Expand All @@ -57,9 +64,11 @@ public static AsyncHttpClient getDefaultInstance() {
}

final ArrayList<AsyncHttpClientMiddleware> mMiddleware = new ArrayList<AsyncHttpClientMiddleware>();

public ArrayList<AsyncHttpClientMiddleware> getMiddleware() {
return mMiddleware;
}

public void insertMiddleware(AsyncHttpClientMiddleware middleware) {
mMiddleware.add(0, middleware);
}
Expand All @@ -68,6 +77,7 @@ public void insertMiddleware(AsyncHttpClientMiddleware middleware) {
AsyncSocketMiddleware socketMiddleware;
HttpTransportMiddleware httpTransportMiddleware;
AsyncServer mServer;

public AsyncHttpClient(AsyncServer server) {
mServer = server;
insertMiddleware(socketMiddleware = new AsyncSocketMiddleware(this));
Expand All @@ -78,15 +88,19 @@ public AsyncHttpClient(AsyncServer server) {

@SuppressLint("NewApi")
private static void setupAndroidProxy(AsyncHttpRequest request) {

// Will only setup a proxy if using wifi
if (!isWifiConnected())
return;

// using a explicit proxy?
if (request.proxyHost != null)
return;

List<Proxy> proxies;
try {
proxies = ProxySelector.getDefault().select(URI.create(request.getUri().toString()));
}
catch (Exception e) {
} catch (Exception e) {
// uri parsing craps itself sometimes.
return;
}
Expand All @@ -101,10 +115,9 @@ private static void setupAndroidProxy(AsyncHttpRequest request) {
String proxyHost;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
proxyHost = proxyAddress.getHostString();
}
else {
} else {
InetAddress address = proxyAddress.getAddress();
if (address!=null)
if (address != null)
proxyHost = address.getHostAddress();
else
proxyHost = proxyAddress.getHostName();
Expand All @@ -131,6 +144,7 @@ public Future<AsyncHttpResponse> execute(String uri, final HttpConnectCallback c
}

private static final String LOGTAG = "AsyncHttp";

private class FutureAsyncHttpResponse extends SimpleFuture<AsyncHttpResponse> {
public AsyncSocket socket;
public Object scheduled;
Expand Down Expand Up @@ -160,8 +174,7 @@ private void reportConnectedCompleted(FutureAsyncHttpResponse cancel, Exception
if (ex != null) {
request.loge("Connection error", ex);
complete = cancel.setComplete(ex);
}
else {
} else {
request.logd("Connection successful");
complete = cancel.setComplete(response);
}
Expand All @@ -181,8 +194,7 @@ private void reportConnectedCompleted(FutureAsyncHttpResponse cancel, Exception
private void execute(final AsyncHttpRequest request, final int redirectCount, final FutureAsyncHttpResponse cancel, final HttpConnectCallback callback) {
if (mServer.isAffinityThread()) {
executeAffinity(request, redirectCount, cancel, callback);
}
else {
} else {
mServer.post(new Runnable() {
@Override
public void run() {
Expand Down Expand Up @@ -218,7 +230,7 @@ private void executeAffinity(final AsyncHttpRequest request, final int redirectC
request.logd("Executing request.");

synchronized (mMiddleware) {
for (AsyncHttpClientMiddleware middleware: mMiddleware) {
for (AsyncHttpClientMiddleware middleware : mMiddleware) {
middleware.onRequest(data);
}
}
Expand Down Expand Up @@ -253,6 +265,7 @@ public void run() {
// 2) wait for a connect
data.connectCallback = new ConnectCallback() {
boolean reported;

@Override
public void onConnectCompleted(Exception ex, AsyncSocket socket) {
if (reported) {
Expand Down Expand Up @@ -299,15 +312,15 @@ public void onConnectCompleted(Exception ex, AsyncSocket socket) {

final Exception unsupportedURI;
synchronized (mMiddleware) {
for (AsyncHttpClientMiddleware middleware: mMiddleware) {
for (AsyncHttpClientMiddleware middleware : mMiddleware) {
Cancellable socketCancellable = middleware.getSocket(data);
if (socketCancellable != null) {
data.socketCancellable = socketCancellable;
cancel.setParent(socketCancellable);
return;
}
}
unsupportedURI = new IllegalArgumentException("invalid uri="+request.getUri()+" middlewares="+mMiddleware);
unsupportedURI = new IllegalArgumentException("invalid uri=" + request.getUri() + " middlewares=" + mMiddleware);
}
reportConnectedCompleted(cancel, unsupportedURI, null, request, callback);
}
Expand Down Expand Up @@ -336,7 +349,7 @@ protected void onRequestCompleted(Exception ex) {
}

synchronized (mMiddleware) {
for (AsyncHttpClientMiddleware middleware: mMiddleware) {
for (AsyncHttpClientMiddleware middleware : mMiddleware) {
middleware.onRequestSent(data);
}
}
Expand All @@ -346,7 +359,7 @@ protected void onRequestCompleted(Exception ex) {
public void setDataEmitter(DataEmitter emitter) {
data.bodyEmitter = emitter;
synchronized (mMiddleware) {
for (AsyncHttpClientMiddleware middleware: mMiddleware) {
for (AsyncHttpClientMiddleware middleware : mMiddleware) {
middleware.onBodyDecoder(data);
}
}
Expand All @@ -363,8 +376,7 @@ public void setDataEmitter(DataEmitter emitter) {
if (redirect.getScheme() == null) {
redirect = Uri.parse(new URL(new URL(request.getUri().toString()), location).toString());
}
}
catch (Exception e) {
} catch (Exception e) {
reportConnectedCompleted(cancel, e, this, request, callback);
return;
}
Expand Down Expand Up @@ -405,7 +417,7 @@ protected void onHeadersReceived() {
request.logv("Received headers:\n" + toString());

synchronized (mMiddleware) {
for (AsyncHttpClientMiddleware middleware: mMiddleware) {
for (AsyncHttpClientMiddleware middleware : mMiddleware) {
middleware.onHeadersReceived(data);
}
}
Expand All @@ -422,7 +434,7 @@ protected void report(Exception ex) {
return;
if (ex instanceof AsyncSSLException) {
request.loge("SSL Exception", ex);
AsyncSSLException ase = (AsyncSSLException)ex;
AsyncSSLException ase = (AsyncSSLException) ex;
request.onHandshakeException(ase);
if (ase.getIgnore())
return;
Expand All @@ -438,7 +450,7 @@ protected void report(Exception ex) {

data.exception = ex;
synchronized (mMiddleware) {
for (AsyncHttpClientMiddleware middleware: mMiddleware) {
for (AsyncHttpClientMiddleware middleware : mMiddleware) {
middleware.onResponseComplete(data);
}
}
Expand Down Expand Up @@ -481,7 +493,7 @@ public void onCompleted(Exception ex) {
ret.setSocket(data.socket);

synchronized (mMiddleware) {
for (AsyncHttpClientMiddleware middleware: mMiddleware) {
for (AsyncHttpClientMiddleware middleware : mMiddleware) {
if (middleware.exchangeHeaders(data))
break;
}
Expand All @@ -492,6 +504,7 @@ public static abstract class RequestCallbackBase<T> implements RequestCallback<T
@Override
public void onProgress(AsyncHttpResponse response, long downloaded, long total) {
}

@Override
public void onConnect(AsyncHttpResponse response) {
}
Expand All @@ -505,7 +518,7 @@ public static abstract class StringCallback extends RequestCallbackBase<String>

public static abstract class JSONObjectCallback extends RequestCallbackBase<JSONObject> {
}

public static abstract class JSONArrayCallback extends RequestCallbackBase<JSONArray> {
}

Expand Down Expand Up @@ -566,8 +579,7 @@ public Future<File> executeFile(AsyncHttpRequest req, final String filename, fin
final OutputStream fout;
try {
fout = new BufferedOutputStream(new FileOutputStream(file), 8192);
}
catch (FileNotFoundException e) {
} catch (FileNotFoundException e) {
SimpleFuture<File> ret = new SimpleFuture<File>();
ret.setComplete(e);
return ret;
Expand All @@ -579,13 +591,11 @@ public void cancelCleanup() {
try {
cancel.get().setDataCallback(new DataCallback.NullDataCallback());
cancel.get().close();
}
catch (Exception e) {
} catch (Exception e) {
}
try {
fout.close();
}
catch (Exception e) {
} catch (Exception e) {
}
file.delete();
}
Expand All @@ -599,8 +609,7 @@ public void onConnectCompleted(Exception ex, final AsyncHttpResponse response) {
if (ex != null) {
try {
fout.close();
}
catch (IOException e) {
} catch (IOException e) {
}
file.delete();
invoke(callback, ret, response, ex, null);
Expand All @@ -623,15 +632,13 @@ public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
public void onCompleted(Exception ex) {
try {
fout.close();
}
catch (IOException e) {
} catch (IOException e) {
ex = e;
}
if (ex != null) {
file.delete();
invoke(callback, ret, response, ex, null);
}
else {
} else {
invoke(callback, ret, response, null, file);
}
}
Expand All @@ -654,12 +661,12 @@ public void onConnectCompleted(Exception ex, final AsyncHttpResponse response) {
invokeConnect(callback, response);

Future<T> parsed = parser.parse(response)
.setCallback(new FutureCallback<T>() {
@Override
public void onCompleted(Exception e, T result) {
invoke(callback, ret, response, e, result);
}
});
.setCallback(new FutureCallback<T>() {
@Override
public void onCompleted(Exception e, T result) {
invoke(callback, ret, response, e, result);
}
});

// reparent to the new parser future
ret.setParent(parsed);
Expand Down Expand Up @@ -690,8 +697,7 @@ public void onConnectCompleted(Exception ex, AsyncHttpResponse response) {
if (ws == null) {
if (!ret.setComplete(new WebSocketHandshakeException("Unable to complete websocket handshake")))
return;
}
else {
} else {
if (!ret.setComplete(ws))
return;
}
Expand All @@ -704,6 +710,26 @@ public void onConnectCompleted(Exception ex, AsyncHttpResponse response) {
return ret;
}

private static boolean isWifiConnected() {
Context context;
try {
context = ContextProvider.getContext();
} catch (NoContextException e) {
Log.i(AsyncHttpClient.class.getSimpleName(), "No Context provided, won't validate wifi");
return false;
}
Object o = null;
if (context != null && context.getApplicationContext() != null) {
o = context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
}
NetworkInfo wifi = null;
if (o != null && o instanceof ConnectivityManager) {
ConnectivityManager connManager = (ConnectivityManager) o;
wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}
return wifi != null && wifi.isConnected();
}

public Future<WebSocket> websocket(String uri, String protocol, final WebSocketConnectCallback callback) {
// assert callback != null;
final AsyncHttpGet get = new AsyncHttpGet(uri.replace("ws://", "http://").replace("wss://", "https://"));
Expand Down
28 changes: 28 additions & 0 deletions AndroidAsync/src/com/koushikdutta/async/util/ContextProvider.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.koushikdutta.async.util;

import android.content.Context;

/**
* Provides a {@link android.content.Context} to check wifi status.
*/
public class ContextProvider {

private static Context context;

private ContextProvider() {
}

public static void createContextProvider(Context context) {
if (ContextProvider.context == null) {
ContextProvider.context = context;
}
}

public static Context getContext() throws NoContextException {
if (ContextProvider.context == null) {
throw new NoContextException();
}
return ContextProvider.context;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.koushikdutta.async.util;

/**
* Handles the scenario where no {@link android.content.Context} is provided.
* Created by jmougan on 19/03/2015.
*/
public class NoContextException extends Exception {
}