/
LoomHTTP.java
222 lines (185 loc) · 7.36 KB
/
LoomHTTP.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package co.theengine.loomdemo;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.util.Base64;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.BinaryHttpResponseHandler;
import java.util.Hashtable;
import java.util.Set;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import org.apache.http.entity.ByteArrayEntity;
import android.util.Log;
/**
* Java Class that exposes Android async HTTP calls
*/
public class LoomHTTP
{
private static final String TAG = "LoomHTTP";
public static void send(final String url, String httpMethod, final long callback, final long payload, byte[] body, final String responseCacheFile, final boolean base64EncodeResponseData, boolean followRedirects)
{
final Activity activity = LoomAdMob.activity;
AsyncHttpClient client = new AsyncHttpClient();
String[] allowedTypes = new String[] {
".*" // Match anything.
};
// iterate over the headers and set them in the client
Set<String> keys = headers.keySet();
for(String key: keys){
client.addHeader(key, (String)headers.get(key));
}
// Set up for saving to response cache file if desired.
File trySaveFile = null;
try
{
trySaveFile = new File(responseCacheFile);
}
catch(Exception e)
{
Log.d(TAG, "Failed to open responseCacheFile " + responseCacheFile);
}
final File savedFile = trySaveFile;
BinaryHttpResponseHandler handler = new BinaryHttpResponseHandler(allowedTypes) {
@Override
public void onSuccess(byte[] binaryData) {
if (responseCacheFile != null && responseCacheFile.length() > 0)
{
Log.d(TAG, "Caching HTTP response to '" + responseCacheFile + "'");
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(savedFile));
bos.write(binaryData);
bos.flush();
bos.close();
Log.d(TAG, "file written...");
}
catch (Exception e)
{
Log.d(TAG, "file write failed...");
throw new AssertionError("HTTP Response could not be cached.");
}
}
final String fResponse;
if (base64EncodeResponseData)
{
fResponse = Base64.encodeToString(binaryData, Base64.NO_WRAP | Base64.NO_PADDING);
}
else
{
try {
fResponse = new String(binaryData, "UTF8");
} catch (UnsupportedEncodingException e) {
throw new AssertionError("UTF-8 is unknown");
}
}
final String rfResponse = fResponse;
// TODO: does this require queueEvent?
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
// Log.d(TAG, "Main view thread submitting '" + rfResponse + "'' from queue!");
LoomHTTP.onSuccess(rfResponse, callback, payload);
}
});
}
@Override
public void onFailure(Throwable error, byte[] binaryData) {
String content;
if (base64EncodeResponseData)
{
content = Base64.encodeToString(binaryData, Base64.NO_WRAP | Base64.NO_PADDING);
}
else
{
try {
content = new String(binaryData, "UTF8");
} catch (UnsupportedEncodingException e) {
throw new AssertionError("UTF-8 is unknown");
}
}
onFailure(error, content);
}
@Override
public void onFailure(Throwable error, String content) {
final String fContent = content;
Log.d("LoomHTTP", "Failed request with message: " + content);
// TODO: does this require queueEvent?
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
LoomHTTP.onFailure(fContent, callback, payload);
}
});
}
};
try
{
if(httpMethod.equals("GET"))
{
client.get(url, handler);
}
else if(httpMethod.equals("POST"))
{
ByteArrayEntity bodyEntity = new ByteArrayEntity(body);
client.post(null, url, bodyEntity, headers.get("Content-Type"), handler);
}
else
{
// TODO: does this require queueEvent?
activity.runOnUiThread(new Runnable()
{
@Override
public void run() {
onFailure("Error: Unknown HTTP Method", callback, payload);
}
});
}
}
catch(Exception e)
{
Log.d("LoomHTTP", "Failed to make request due to: " + e.toString());
// TODO: does this require queueEvent?
activity.runOnUiThread(new Runnable()
{
@Override
public void run() {
onFailure("Error: exception caught when posting request!", callback, payload);
}
});
}
// clear the headers after each send();
headers.clear();
}
/**
* Adds a header to the headers list, which will be consumed when send() is called.
*/
public static void addHeader(String key, String value)
{
headers.put(key, value);
}
public static boolean isConnected()
{
// Via http://stackoverflow.com/a/8845364/809422
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) LoomAdMob.activity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnectedOrConnecting())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnectedOrConnecting())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
private static native void onSuccess(String data, long callback, long payload);
private static native void onFailure(String data, long callback, long payload);
// java representation of headers. These are cleared after each send() call.
protected static Hashtable<String, String> headers = new Hashtable<String, String>();
}