Skip to content

Commit b6d27f6

Browse files
hamidhamid
authored andcommitted
add offline request
1 parent 6e91a82 commit b6d27f6

File tree

7 files changed

+212
-16
lines changed

7 files changed

+212
-16
lines changed

.classpath

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
<?xml version="1.0" encoding="UTF-8"?>
22
<classpath>
33
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
4+
<classpathentry kind="src" path="examples"/>
45
<classpathentry kind="src" path="src"/>
56
<classpathentry kind="src" path="gen"/>
6-
<classpathentry kind="src" path="examples"/>
7+
<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
78
<classpathentry kind="output" path="bin/classes"/>
89
</classpath>

project.properties

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,4 @@
99

1010
android.library=true
1111
# Project target.
12-
target=android-3
12+
target=android-17

src/com/loopj/android/http/AsyncHttpClient.java

Lines changed: 49 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@
2020

2121
import java.io.IOException;
2222
import java.io.InputStream;
23+
import java.io.UnsupportedEncodingException;
2324
import java.lang.ref.WeakReference;
25+
import java.security.NoSuchAlgorithmException;
2426
import java.util.HashMap;
2527
import java.util.LinkedList;
2628
import java.util.List;
@@ -335,7 +337,28 @@ public void get(Context context, String url, AsyncHttpResponseHandler responseHa
335337
* @param responseHandler the response handler instance that should handle the response.
336338
*/
337339
public void get(Context context, String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
338-
sendRequest(httpClient, httpContext, new HttpGet(getUrlWithQueryString(url, params)), null, responseHandler, context);
340+
341+
String completeUrl = getUrlWithQueryString(url, params);
342+
343+
responseHandler.setUrl(completeUrl);
344+
345+
if(responseHandler.isForcedToReadFromCacheEnabled()){
346+
347+
byte[] dataFromCache = null;
348+
349+
try {
350+
dataFromCache = CacheManager.retrieveData(responseHandler.getAppContex(), CacheManager.SHA1(completeUrl));
351+
} catch (Exception e) {
352+
e.printStackTrace();
353+
}
354+
355+
if(dataFromCache!=null){
356+
responseHandler.handleSuccessMessage(2000, new String(dataFromCache) ,true);
357+
return;
358+
}
359+
}
360+
361+
sendRequest(httpClient, httpContext, new HttpGet(getUrlWithQueryString(url, params)), null, responseHandler, context);
339362
}
340363

341364
/**
@@ -349,13 +372,34 @@ public void get(Context context, String url, RequestParams params, AsyncHttpResp
349372
* the response.
350373
*/
351374
public void get(Context context, String url, Header[] headers, RequestParams params, AsyncHttpResponseHandler responseHandler) {
352-
HttpUriRequest request = new HttpGet(getUrlWithQueryString(url, params));
375+
376+
String completeUrl = getUrlWithQueryString(url, params);
377+
378+
responseHandler.setUrl(completeUrl);
379+
380+
if(responseHandler.isForcedToReadFromCacheEnabled()){
381+
382+
byte[] dataFromCache = null;
383+
384+
try {
385+
dataFromCache = CacheManager.retrieveData(responseHandler.getAppContex(), CacheManager.SHA1(completeUrl));
386+
} catch (Exception e) {
387+
e.printStackTrace();
388+
}
389+
390+
if(dataFromCache!=null){
391+
responseHandler.handleSuccessMessage(2000, new String(dataFromCache) ,true);
392+
return;
393+
}
394+
}
395+
396+
397+
HttpUriRequest request = new HttpGet(completeUrl);
353398
if(headers != null) request.setHeaders(headers);
354-
sendRequest(httpClient, httpContext, request, null, responseHandler,
355-
context);
399+
sendRequest(httpClient, httpContext, request, null, responseHandler, context);
356400
}
357401

358-
402+
359403
//
360404
// HTTP POST Requests
361405
//

src/com/loopj/android/http/AsyncHttpResponseHandler.java

Lines changed: 42 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818

1919
package com.loopj.android.http;
2020

21+
import android.content.Context;
22+
import android.net.http.HttpResponseCache;
2123
import android.os.Handler;
2224
import android.os.Looper;
2325
import android.os.Message;
@@ -29,6 +31,8 @@
2931
import org.apache.http.util.EntityUtils;
3032

3133
import java.io.IOException;
34+
import java.io.UnsupportedEncodingException;
35+
import java.security.NoSuchAlgorithmException;
3236

3337
/**
3438
* Used to intercept and handle the responses from requests made using
@@ -72,6 +76,10 @@ public class AsyncHttpResponseHandler {
7276
protected static final int FINISH_MESSAGE = 3;
7377

7478
private Handler handler;
79+
80+
private Context mContext;
81+
private Boolean mCacheRequest = false;
82+
private String mURL;
7583

7684
/**
7785
* Creates a new AsyncHttpResponseHandler
@@ -87,7 +95,24 @@ public void handleMessage(Message msg){
8795
}
8896
}
8997

90-
98+
public AsyncHttpResponseHandler(Context context,boolean cacheRequest) {
99+
this();
100+
mContext = context;
101+
mCacheRequest=cacheRequest;
102+
}
103+
104+
public Context getAppContex(){
105+
return mContext;
106+
}
107+
108+
public boolean isForcedToReadFromCacheEnabled(){
109+
return mCacheRequest;
110+
}
111+
112+
public void setUrl(String url){
113+
mURL = url;
114+
}
115+
91116
//
92117
// Callbacks to be overridden, typically anonymously
93118
//
@@ -106,15 +131,18 @@ public void onFinish() {}
106131
* Fired when a request returns successfully, override to handle in your own code
107132
* @param content the body of the HTTP response from the server
108133
*/
109-
public void onSuccess(String content) {}
134+
public void onSuccess(String content) {
135+
136+
}
110137

111138
/**
112139
* Fired when a request returns successfully, override to handle in your own code
113140
* @param statusCode the status code of the response
114141
* @param content the body of the HTTP response from the server
115142
*/
116-
public void onSuccess(int statusCode, String content) {
117-
onSuccess(content);
143+
public void onSuccess(int statusCode, String content,boolean isFromCache) {
144+
145+
onSuccess(content);
118146
}
119147

120148
/**
@@ -164,8 +192,10 @@ protected void sendFinishMessage() {
164192
// Pre-processing of messages (in original calling thread, typically the UI thread)
165193
//
166194

167-
protected void handleSuccessMessage(int statusCode, String responseBody) {
168-
onSuccess(statusCode, responseBody);
195+
196+
protected void handleSuccessMessage(int statusCode, String responseBody,boolean isFromCache) {
197+
198+
onSuccess(statusCode, responseBody,isFromCache);
169199
}
170200

171201
protected void handleFailureMessage(Throwable e, String responseBody) {
@@ -181,7 +211,12 @@ protected void handleMessage(Message msg) {
181211
switch(msg.what) {
182212
case SUCCESS_MESSAGE:
183213
response = (Object[])msg.obj;
184-
handleSuccessMessage(((Integer) response[0]).intValue(), (String) response[1]);
214+
try {
215+
CacheManager.cacheData(mContext, ((String) response[1]).getBytes() ,CacheManager.SHA1(mURL));
216+
} catch (Exception e) {
217+
e.printStackTrace();
218+
}
219+
handleSuccessMessage(((Integer) response[0]).intValue(), (String) response[1],false);
185220
break;
186221
case FAILURE_MESSAGE:
187222
response = (Object[])msg.obj;

src/com/loopj/android/http/BinaryHttpResponseHandler.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ public void onSuccess(byte[] binaryData) {}
9595
public void onSuccess(int statusCode, byte[] binaryData) {
9696
onSuccess(binaryData);
9797
}
98+
9899

99100
/**
100101
* Fired when a request fails to complete, override to handle in your own code
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
package com.loopj.android.http;
2+
3+
import java.io.File;
4+
import java.io.FileInputStream;
5+
import java.io.FileOutputStream;
6+
import java.io.IOException;
7+
import java.io.UnsupportedEncodingException;
8+
import java.security.MessageDigest;
9+
import java.security.NoSuchAlgorithmException;
10+
11+
import android.content.Context;
12+
import android.util.Log;
13+
14+
public class CacheManager {
15+
16+
private static final long MAX_SIZE = 5242880L; // 5MB
17+
18+
private CacheManager() {
19+
20+
}
21+
22+
public static void cacheData(Context context, byte[] data, String name) throws IOException {
23+
24+
File cacheDir = context.getCacheDir();
25+
long size = getDirSize(cacheDir);
26+
long newSize = data.length + size;
27+
28+
if (newSize > MAX_SIZE) {
29+
cleanDir(cacheDir, newSize - MAX_SIZE);
30+
}
31+
Log.i("hamid", "cacheData");
32+
File file = new File(cacheDir, name);
33+
FileOutputStream os = new FileOutputStream(file);
34+
try {
35+
os.write(data);
36+
}finally {
37+
os.flush();
38+
os.close();
39+
}
40+
}
41+
42+
public static byte[] retrieveData(Context context, String name) throws IOException {
43+
44+
File cacheDir = context.getCacheDir();
45+
File file = new File(cacheDir, name);
46+
47+
if (!file.exists()) {
48+
Log.i("hamid", "retrieveData cache does not exist");
49+
// Data doesn't exist
50+
return null;
51+
}
52+
53+
Log.i("hamid", "retrieveData cache exist");
54+
55+
byte[] data = new byte[(int) file.length()];
56+
FileInputStream is = new FileInputStream(file);
57+
try {
58+
is.read(data);
59+
}
60+
finally {
61+
is.close();
62+
}
63+
64+
return data;
65+
}
66+
67+
private static void cleanDir(File dir, long bytes) {
68+
69+
long bytesDeleted = 0;
70+
File[] files = dir.listFiles();
71+
72+
for (File file : files) {
73+
bytesDeleted += file.length();
74+
file.delete();
75+
76+
if (bytesDeleted >= bytes) {
77+
break;
78+
}
79+
}
80+
}
81+
82+
private static long getDirSize(File dir) {
83+
84+
long size = 0;
85+
File[] files = dir.listFiles();
86+
87+
for (File file : files) {
88+
if (file.isFile()) {
89+
size += file.length();
90+
}
91+
}
92+
93+
return size;
94+
}
95+
96+
private static String convertToHex(byte[] data) {
97+
StringBuilder buf = new StringBuilder();
98+
for (byte b : data) {
99+
int halfbyte = (b >>> 4) & 0x0F;
100+
int two_halfs = 0;
101+
do {
102+
buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
103+
halfbyte = b & 0x0F;
104+
} while (two_halfs++ < 1);
105+
}
106+
return buf.toString();
107+
}
108+
109+
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
110+
MessageDigest md = MessageDigest.getInstance("SHA-1");
111+
md.update(text.getBytes("iso-8859-1"), 0, text.length());
112+
byte[] sha1hash = md.digest();
113+
return convertToHex(sha1hash);
114+
}
115+
116+
}

src/com/loopj/android/http/SyncHttpClient.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,7 @@ protected void sendRequest(DefaultHttpClient client,
6262
/*
6363
* will execute the request directly
6464
*/
65-
new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler)
66-
.run();
65+
new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler).run();
6766
}
6867

6968
public abstract String onRequestFailed(Throwable error, String content);

0 commit comments

Comments
 (0)