Skip to content

Commit 619f9c0

Browse files
committed
Initial commit
0 parents  commit 619f9c0

File tree

10 files changed

+628
-0
lines changed

10 files changed

+628
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
build.num

README.md

Whitespace-only changes.

build.xml

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<project default="package">
2+
<property name="version.num" value="1.0.0" />
3+
<buildnumber file="build.num" />
4+
<property name="lib.dir" value="/usr/local/android_sdk/platforms/android-7/" />
5+
<property name="build.dir" value="./build"/>
6+
<property name="classes.dir" value="${build.dir}/classes"/>
7+
8+
<path id="classpath">
9+
<fileset dir="${lib.dir}" includes="**/*.jar" />
10+
</path>
11+
12+
<target name="compile">
13+
<mkdir dir="${build.dir}" />
14+
<mkdir dir="${classes.dir}" />
15+
<javac srcdir="src" destdir="${classes.dir}" classpathref="classpath" includeantruntime="false">
16+
<compilerarg value="-Xlint:unchecked"/>
17+
</javac>
18+
</target>
19+
20+
<target name="jar" depends="compile">
21+
<delete file="async-http.jar" />
22+
<delete file="MANIFEST.MF" />
23+
<manifest file="MANIFEST.MF">
24+
<attribute name="Built-By" value="${user.name}" />
25+
<attribute name="Implementation-Version" value="${version.num}-b${build.number}"/>
26+
</manifest>
27+
28+
<jar destfile="async-http.jar" basedir="build/classes" includes="**/*.class" manifest="MANIFEST.MF" />
29+
</target>
30+
31+
<target name="clean">
32+
<delete dir="build" />
33+
<delete>
34+
<fileset dir="." includes="async-http.jar*"/>
35+
<fileset file="MANIFEST.MF"/>
36+
</delete>
37+
</target>
38+
39+
<target name="package" depends="compile,jar" />
40+
</project>

examples/ExampleRestClient.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import java.util.Locale;
2+
3+
import com.loopj.android.http.AsyncHttpClient;
4+
import com.loopj.android.http.AsyncHttpRequest;
5+
import com.loopj.android.http.AsyncHttpParams;
6+
7+
class ExampleRestClient {
8+
private static final String USER_AGENT = "Example Android Rest Client";
9+
private static final String BASE_URL = "http://api.example.com/";
10+
11+
private static AsyncHttpClient client;
12+
13+
static {
14+
client = new AsyncHttpClient(USER_AGENT);
15+
client.setCookieStore(new PersistentCookieStore(AndroidApplication.getContext()));
16+
}
17+
18+
public static void get(String url, AsyncHttpParams params, AsyncHttpRequest.OnResponseHandler responseHandler) {
19+
client.get(getAbsoluteUrl(url), augmentParams(params), responseHandler);
20+
}
21+
22+
public static void post(String url, AsyncHttpParams params, AsyncHttpRequest.OnResponseHandler responseHandler) {
23+
client.get(getAbsoluteUrl(url), augmentParams(params), responseHandler);
24+
}
25+
26+
private static String getAbsoluteUrl(String relativeUrl) {
27+
return BASE_URL + relativeUrl;
28+
}
29+
30+
private static AsyncHttpParams augmentParams(AsyncHttpParams params) {
31+
if(params == null) {
32+
params = new AsyncHttpParams();
33+
}
34+
35+
// Add locale info to every request
36+
Locale currentLocale = Locale.getDefault();
37+
params.put("country_code", currentLocale.getISO3Country());
38+
params.put("language_code", currentLocale.getISO3Language());
39+
40+
return params;
41+
}
42+
}

examples/ExampleUsage.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import com.loopj.android.http.AsyncHttpClient;
2+
import com.loopj.android.http.AsyncHttpRequest;
3+
4+
class ExampleUsage {
5+
public static void makeRequest() {
6+
AsyncHttpClient client = new AsyncHttpClient("My User Agent");
7+
client.get("http://www.google.com", new AsyncHttpRequest.OnResponseHandler() {
8+
@Override
9+
public void onSuccess(String response) {
10+
Log.d("ExampleUsage", response);
11+
}
12+
});
13+
}
14+
}
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
package com.loopj.android.http;
2+
3+
import java.io.IOException;
4+
import java.io.InputStream;
5+
import java.util.concurrent.ExecutorService;
6+
import java.util.concurrent.Executors;
7+
import java.util.zip.GZIPInputStream;
8+
9+
import org.apache.http.Header;
10+
import org.apache.http.HeaderElement;
11+
import org.apache.http.HttpEntity;
12+
import org.apache.http.HttpRequest;
13+
import org.apache.http.HttpRequestInterceptor;
14+
import org.apache.http.HttpResponse;
15+
import org.apache.http.HttpResponseInterceptor;
16+
import org.apache.http.HttpVersion;
17+
import org.apache.http.client.CookieStore;
18+
import org.apache.http.client.methods.HttpGet;
19+
import org.apache.http.client.methods.HttpPost;
20+
import org.apache.http.client.methods.HttpRequestBase;
21+
import org.apache.http.client.protocol.ClientContext;
22+
import org.apache.http.conn.params.ConnManagerParams;
23+
import org.apache.http.conn.params.ConnPerRouteBean;
24+
import org.apache.http.conn.scheme.PlainSocketFactory;
25+
import org.apache.http.conn.scheme.Scheme;
26+
import org.apache.http.conn.scheme.SchemeRegistry;
27+
import org.apache.http.conn.ssl.SSLSocketFactory;
28+
import org.apache.http.entity.HttpEntityWrapper;
29+
import org.apache.http.impl.client.DefaultHttpClient;
30+
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
31+
import org.apache.http.params.BasicHttpParams;
32+
import org.apache.http.params.HttpConnectionParams;
33+
import org.apache.http.params.HttpProtocolParams;
34+
import org.apache.http.protocol.BasicHttpContext;
35+
import org.apache.http.protocol.SyncBasicHttpContext;
36+
import org.apache.http.protocol.HttpContext;
37+
38+
public class AsyncHttpClient {
39+
public static final int DEFAULT_MAX_CONNECTIONS = 4;
40+
public static final int DEFAULT_SOCKET_TIMEOUT = 30 * 1000;
41+
private static final String ENCODING = "UTF-8";
42+
private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
43+
private static final String ENCODING_GZIP = "gzip";
44+
45+
private static int maxConnections = DEFAULT_MAX_CONNECTIONS;
46+
private static int socketTimeout = DEFAULT_SOCKET_TIMEOUT;
47+
48+
private DefaultHttpClient httpClient;
49+
private HttpContext httpContext;
50+
private ExecutorService threadPool;
51+
52+
public AsyncHttpClient(String userAgent) {
53+
BasicHttpParams httpParams = new BasicHttpParams();
54+
55+
ConnManagerParams.setTimeout(httpParams, socketTimeout);
56+
ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
57+
ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);
58+
59+
HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
60+
HttpConnectionParams.setTcpNoDelay(httpParams, true);
61+
62+
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
63+
HttpProtocolParams.setUserAgent(httpParams, userAgent);
64+
65+
SchemeRegistry schemeRegistry = new SchemeRegistry();
66+
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
67+
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
68+
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
69+
70+
threadPool = Executors.newCachedThreadPool();
71+
httpContext = new SyncBasicHttpContext(new BasicHttpContext());
72+
httpClient = new DefaultHttpClient(cm, httpParams);
73+
httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
74+
public void process(HttpRequest request, HttpContext context) {
75+
if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
76+
request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
77+
}
78+
}
79+
});
80+
81+
httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
82+
public void process(HttpResponse response, HttpContext context) {
83+
final HttpEntity entity = response.getEntity();
84+
final Header encoding = entity.getContentEncoding();
85+
if (encoding != null) {
86+
for (HeaderElement element : encoding.getElements()) {
87+
if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
88+
response.setEntity(new InflatingEntity(response.getEntity()));
89+
break;
90+
}
91+
}
92+
}
93+
}
94+
});
95+
}
96+
97+
public void setCookieStore(CookieStore cookieStore) {
98+
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
99+
}
100+
101+
public void get(String url, AsyncHttpRequest.OnResponseHandler responseHandler) {
102+
get(url, null, responseHandler);
103+
}
104+
105+
public void get(String url, AsyncHttpParams params, AsyncHttpRequest.OnResponseHandler responseHandler) {
106+
// Build and append query string (utf8 url encoded)
107+
if(params != null) {
108+
String paramString = params.getParamString();
109+
url += "?" + paramString;
110+
}
111+
112+
// Fire up the request in a new thread
113+
executeAsyncRequest(new HttpGet(url), responseHandler);
114+
}
115+
116+
public void post(String url, AsyncHttpRequest.OnResponseHandler responseHandler) {
117+
post(url, null, responseHandler);
118+
}
119+
120+
public void post(String url, AsyncHttpParams params, AsyncHttpRequest.OnResponseHandler responseHandler) {
121+
// Build post object with params
122+
final HttpPost post = new HttpPost(url);
123+
if(params != null) {
124+
HttpEntity entity = params.getEntity();
125+
if(entity != null){
126+
post.setEntity(entity);
127+
}
128+
}
129+
130+
// Fire up the request in a new thread
131+
executeAsyncRequest(post, responseHandler);
132+
}
133+
134+
private void executeAsyncRequest(final HttpRequestBase request, final AsyncHttpRequest.OnResponseHandler responseHandler) {
135+
threadPool.execute(new AsyncHttpRequest(httpClient, httpContext, request, responseHandler));
136+
}
137+
138+
private static class InflatingEntity extends HttpEntityWrapper {
139+
public InflatingEntity(HttpEntity wrapped) {
140+
super(wrapped);
141+
}
142+
143+
@Override
144+
public InputStream getContent() throws IOException {
145+
return new GZIPInputStream(wrappedEntity.getContent());
146+
}
147+
148+
@Override
149+
public long getContentLength() {
150+
return -1;
151+
}
152+
}
153+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package com.loopj.android.http;
2+
3+
import java.io.UnsupportedEncodingException;
4+
import java.util.LinkedList;
5+
import java.util.List;
6+
import java.util.concurrent.ConcurrentHashMap;
7+
8+
import org.apache.http.HttpEntity;
9+
import org.apache.http.client.entity.UrlEncodedFormEntity;
10+
import org.apache.http.client.utils.URLEncodedUtils;
11+
import org.apache.http.message.BasicNameValuePair;
12+
13+
public class AsyncHttpParams {
14+
private static String ENCODING = "UTF-8";
15+
16+
private ConcurrentHashMap<String,String> urlParams;
17+
18+
public AsyncHttpParams() {
19+
init();
20+
}
21+
22+
public AsyncHttpParams(String key, String value) {
23+
init();
24+
put(key, value);
25+
}
26+
27+
public void put(String key, String value){
28+
urlParams.put(key,value);
29+
}
30+
31+
public void remove(String key){
32+
urlParams.remove(key);
33+
}
34+
35+
public String getParamString() {
36+
return URLEncodedUtils.format(getParamsList(), ENCODING);
37+
}
38+
39+
public HttpEntity getEntity() {
40+
HttpEntity entity = null;
41+
try {
42+
entity = new UrlEncodedFormEntity(getParamsList(), ENCODING);
43+
} catch (UnsupportedEncodingException e) {
44+
e.printStackTrace();
45+
}
46+
return entity;
47+
}
48+
49+
private void init(){
50+
urlParams = new ConcurrentHashMap<String,String>();
51+
}
52+
53+
private List<BasicNameValuePair> getParamsList() {
54+
List<BasicNameValuePair> lparams = new LinkedList<BasicNameValuePair>();
55+
56+
for(ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
57+
lparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
58+
}
59+
60+
return lparams;
61+
}
62+
}

0 commit comments

Comments
 (0)