aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/network/Network.java
diff options
context:
space:
mode:
Diffstat (limited to 'main/src/cgeo/geocaching/network/Network.java')
-rw-r--r--main/src/cgeo/geocaching/network/Network.java303
1 files changed, 117 insertions, 186 deletions
diff --git a/main/src/cgeo/geocaching/network/Network.java b/main/src/cgeo/geocaching/network/Network.java
index 502db33..bb5a949 100644
--- a/main/src/cgeo/geocaching/network/Network.java
+++ b/main/src/cgeo/geocaching/network/Network.java
@@ -1,13 +1,9 @@
package cgeo.geocaching.network;
-import cgeo.geocaching.Settings;
-import cgeo.geocaching.cgBase;
-import cgeo.geocaching.enumerations.StatusCode;
import cgeo.geocaching.files.LocalStorage;
import cgeo.geocaching.utils.BaseUtils;
import cgeo.geocaching.utils.Log;
-import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
@@ -18,17 +14,13 @@ import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.NameValuePair;
-import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
-import org.apache.http.cookie.Cookie;
import org.apache.http.entity.HttpEntityWrapper;
-import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
@@ -44,11 +36,10 @@ import android.net.Uri;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
-import java.util.List;
import java.util.zip.GZIPInputStream;
-
public abstract class Network {
static class GzipDecompressingEntity extends HttpEntityWrapper {
@@ -76,8 +67,6 @@ public abstract class Network {
private static final String PATTERN_PASSWORD = "(?<=[\\?&])[Pp]ass(w(or)?d)?=[^&#$]+";
private final static HttpParams clientParams = new BasicHttpParams();
- private static boolean cookieStoreRestored = false;
- private final static CookieStore cookieStore = new BasicCookieStore();
static {
Network.clientParams.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
@@ -91,7 +80,7 @@ public abstract class Network {
private static HttpClient getHttpClient() {
final DefaultHttpClient client = new DefaultHttpClient();
- client.setCookieStore(cookieStore);
+ client.setCookieStore(Cookies.cookieStore);
client.setParams(clientParams);
client.addRequestInterceptor(new HttpRequestInterceptor() {
@@ -117,7 +106,7 @@ public abstract class Network {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
- Log.d(Settings.tag, "Decompressing response");
+ Log.d("Decompressing response");
response.setEntity(
new Network.GzipDecompressingEntity(response.getEntity()));
return;
@@ -132,40 +121,6 @@ public abstract class Network {
return client;
}
- public static void restoreCookieStore(final String oldCookies) {
- if (!cookieStoreRestored) {
- Network.clearCookies();
- if (oldCookies != null) {
- for (final String cookie : StringUtils.split(oldCookies, ';')) {
- final String[] split = StringUtils.split(cookie, "=", 3);
- if (split.length == 3) {
- final BasicClientCookie newCookie = new BasicClientCookie(split[0], split[1]);
- newCookie.setDomain(split[2]);
- cookieStore.addCookie(newCookie);
- }
- }
- }
- cookieStoreRestored = true;
- }
- }
-
- public static String dumpCookieStore() {
- StringBuilder cookies = new StringBuilder();
- for (final Cookie cookie : cookieStore.getCookies()) {
- cookies.append(cookie.getName());
- cookies.append('=');
- cookies.append(cookie.getValue());
- cookies.append('=');
- cookies.append(cookie.getDomain());
- cookies.append(';');
- }
- return cookies.toString();
- }
-
- public static void clearCookies() {
- cookieStore.clear();
- }
-
/**
* POST HTTP request
*
@@ -173,117 +128,148 @@ public abstract class Network {
* @param params
* @return
*/
- public static HttpResponse postRequest(final String uri, final List<? extends NameValuePair> params) {
- try {
- HttpPost request = new HttpPost(uri);
- if (params != null) {
- request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
- }
- request.setHeader("X-Requested-With", "XMLHttpRequest");
- return Network.request(request);
- } catch (Exception e) {
- // Can be UnsupportedEncodingException, ClientProtocolException or IOException
- Log.e(Settings.tag, "postRequest", e);
- return null;
- }
- }
-
- /**
- * GET HTTP request
- *
- * @param uri
- * @param params
- * @param xContentType
- * @param my
- * @param addF
- * @return
- */
- public static HttpResponse request(final String uri, final Parameters params, boolean xContentType, boolean my, boolean addF) {
- return Network.request(uri, cgBase.addFToParams(params, my, addF), xContentType);
+ public static HttpResponse postRequest(final String uri, final Parameters params) {
+ return request("POST", uri, params, null, null);
}
/**
- * GET HTTP request
+ * Make an HTTP request
*
+ * @param method
+ * the HTTP method to use ("GET" or "POST")
* @param uri
+ * the URI to request
* @param params
- * @param xContentType
+ * the parameters to add the the GET request
+ * @param headers
+ * the headers to add to the GET request
* @param cacheFile
- * the name of the file storing the cached resource, or null not to use one
- * @return
+ * the cache file used to cache this query
+ * @return the HTTP response, or null in case of an encoding error in a POST request arguments
*/
- public static HttpResponse request(final String uri, final Parameters params, final boolean xContentType, final File cacheFile) {
- final String fullUri = params == null ? uri : Uri.parse(uri).buildUpon().encodedQuery(params.toString()).build().toString();
- final HttpRequestBase request = new HttpGet(fullUri);
+ private static HttpResponse request(final String method, final String uri, final Parameters params, final Parameters headers, final File cacheFile) {
+ HttpRequestBase request;
+ if (method.equals("GET")) {
+ final String fullUri = params == null ? uri : Uri.parse(uri).buildUpon().encodedQuery(params.toString()).build().toString();
+ request = new HttpGet(fullUri);
+ } else {
+ request = new HttpPost(uri);
+ if (params != null) {
+ try {
+ ((HttpPost) request).setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
+ } catch (final UnsupportedEncodingException e) {
+ Log.e("request", e);
+ return null;
+ }
+ }
+ }
- request.setHeader("X-Requested-With", "XMLHttpRequest");
+ for (final NameValuePair header : Parameters.extend(Parameters.merge(headers, cacheHeaders(cacheFile)),
+ "Accept-Charset", "utf-8,iso-8859-1;q=0.8,utf-16;q=0.8,*;q=0.7",
+ "Accept-Language", "en-US,*;q=0.9",
+ "X-Requested-With", "XMLHttpRequest")) {
+ request.setHeader(header.getName(), header.getValue());
+ }
+
+ request.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Network.USER_AGENT);
- if (xContentType) {
- request.setHeader("Content-Type", "application/x-www-form-urlencoded");
+ final String reqLogStr = request.getMethod() + " " + Network.hidePassword(request.getURI().toString());
+ Log.d(reqLogStr);
+
+ final HttpClient client = Network.getHttpClient();
+ for (int i = 0; i <= Network.NB_DOWNLOAD_RETRIES; i++) {
+ final long before = System.currentTimeMillis();
+ try {
+ final HttpResponse response = client.execute(request);
+ int status = response.getStatusLine().getStatusCode();
+ if (status == 200) {
+ Log.d(status + Network.formatTimeSpan(before) + reqLogStr);
+ } else {
+ Log.w(status + " [" + response.getStatusLine().getReasonPhrase() + "]" + Network.formatTimeSpan(before) + reqLogStr);
+ }
+ return response;
+ } catch (IOException e) {
+ final String timeSpan = Network.formatTimeSpan(before);
+ final String tries = (i + 1) + "/" + (Network.NB_DOWNLOAD_RETRIES + 1);
+ if (i == Network.NB_DOWNLOAD_RETRIES) {
+ Log.e("Failure " + tries + timeSpan + reqLogStr, e);
+ } else {
+ Log.e("Failure " + tries + " (" + e.toString() + ")" + timeSpan + "- retrying " + reqLogStr);
+ }
+ }
}
+ return null;
+ }
+
+ private static Parameters cacheHeaders(final File cacheFile) {
if (cacheFile != null && cacheFile.exists()) {
final String etag = LocalStorage.getSavedHeader(cacheFile, "etag");
if (etag != null) {
- request.setHeader("If-None-Match", etag);
+ return new Parameters("If-None-Match", etag);
} else {
final String lastModified = LocalStorage.getSavedHeader(cacheFile, "last-modified");
if (lastModified != null) {
- request.setHeader("If-Modified-Since", lastModified);
+ return new Parameters("If-Modified-Since", lastModified);
}
}
}
-
- return Network.request(request);
+ return null;
}
/**
* GET HTTP request
*
* @param uri
+ * the URI to request
* @param params
- * @param xContentType
- * @return
+ * the parameters to add the the GET request
+ * @param cacheFile
+ * the name of the file storing the cached resource, or null not to use one
+ * @return the HTTP response
*/
- public static HttpResponse request(final String uri, final Parameters params, final boolean xContentType) {
- return request(uri, params, xContentType, null);
+ public static HttpResponse getRequest(final String uri, final Parameters params, final File cacheFile) {
+ return request("GET", uri, params, null, cacheFile);
}
- public static HttpResponse request(final HttpRequestBase request) {
- request.setHeader("Accept-Charset", "utf-8,iso-8859-1;q=0.8,utf-16;q=0.8,*;q=0.7");
- request.setHeader("Accept-Language", "en-US,*;q=0.9");
- request.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT);
- return Network.doRequest(request);
- }
- private static HttpResponse doRequest(final HttpRequestBase request) {
- final String reqLogStr = request.getMethod() + " " + hidePassword(request.getURI().toString());
- Log.d(Settings.tag, reqLogStr);
+ /**
+ * GET HTTP request
+ *
+ * @param uri
+ * the URI to request
+ * @param params
+ * the parameters to add the the GET request
+ * @return the HTTP response
+ */
+ public static HttpResponse getRequest(final String uri, final Parameters params) {
+ return request("GET", uri, params, null, null);
+ }
- final HttpClient client = getHttpClient();
- for (int i = 0; i <= NB_DOWNLOAD_RETRIES; i++) {
- final long before = System.currentTimeMillis();
- try {
- final HttpResponse response = client.execute(request);
- int status = response.getStatusLine().getStatusCode();
- if (status == 200) {
- Log.d(Settings.tag, status + Network.formatTimeSpan(before) + reqLogStr);
- } else {
- Log.w(Settings.tag, status + " [" + response.getStatusLine().getReasonPhrase() + "]" + Network.formatTimeSpan(before) + reqLogStr);
- }
- return response;
- } catch (IOException e) {
- final String timeSpan = Network.formatTimeSpan(before);
- final String tries = (i + 1) + "/" + (NB_DOWNLOAD_RETRIES + 1);
- if (i == NB_DOWNLOAD_RETRIES) {
- Log.e(Settings.tag, "Failure " + tries + timeSpan + reqLogStr, e);
- } else {
- Log.e(Settings.tag, "Failure " + tries + " (" + e.toString() + ")" + timeSpan + "- retrying " + reqLogStr);
- }
- }
- }
+ /**
+ * GET HTTP request
+ *
+ * @param uri
+ * the URI to request
+ * @param params
+ * the parameters to add the the GET request
+ * @param headers
+ * the headers to add to the GET request
+ * @return the HTTP response
+ */
+ public static HttpResponse getRequest(final String uri, final Parameters params, final Parameters headers) {
+ return request("GET", uri, params, headers, null);
+ }
- return null;
+ /**
+ * GET HTTP request
+ *
+ * @param uri
+ * the URI to request
+ * @return the HTTP response
+ */
+ public static HttpResponse getRequest(final String uri) {
+ return request("GET", uri, null, null, null);
}
private static String formatTimeSpan(final long before) {
@@ -296,33 +282,24 @@ public abstract class Network {
}
public static JSONObject requestJSON(final String uri, final Parameters params) {
- final HttpGet request = new HttpGet(Network.prepareParameters(uri, params));
- request.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
- request.setHeader("Content-Type", "application/json; charset=UTF-8");
- request.setHeader("X-Requested-With", "XMLHttpRequest");
-
- final HttpResponse response = doRequest(request);
- if (response != null && response.getStatusLine().getStatusCode() == 200) {
+ final HttpResponse response = request("GET", uri, params, new Parameters("Accept", "application/json, text/javascript, */*; q=0.01"), null);
+ if (isSuccess(response)) {
try {
return new JSONObject(Network.getResponseData(response));
- } catch (JSONException e) {
- Log.e(Settings.tag, "Network.requestJSON", e);
+ } catch (final JSONException e) {
+ Log.e("Network.requestJSON", e);
}
}
return null;
}
- private static String prepareParameters(final String baseUri, final Parameters params) {
- return CollectionUtils.isNotEmpty(params) ? baseUri + "?" + params.toString() : baseUri;
- }
-
private static String getResponseDataNoError(final HttpResponse response, boolean replaceWhitespace) {
try {
String data = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
return replaceWhitespace ? BaseUtils.replaceWhitespace(data) : data;
} catch (Exception e) {
- Log.e(Settings.tag, "getResponseData", e);
+ Log.e("getResponseData", e);
return null;
}
}
@@ -331,59 +308,13 @@ public abstract class Network {
return Network.getResponseData(response, true);
}
- static public String getResponseData(final HttpResponse response, boolean replaceWhitespace) {
+ public static String getResponseData(final HttpResponse response, boolean replaceWhitespace) {
if (!isSuccess(response)) {
return null;
}
return getResponseDataNoError(response, replaceWhitespace);
}
- /**
- * POST HTTP request. Do the request a second time if the user is not logged in
- *
- * @param uri
- * @return
- */
- public static String postRequestLogged(final String uri) {
- HttpResponse response = postRequest(uri, null);
- String data = getResponseData(response);
-
- if (!Login.getLoginStatus(data)) {
- if (Login.login() == StatusCode.NO_ERROR) {
- response = postRequest(uri, null);
- data = getResponseData(response);
- } else {
- Log.i(Settings.tag, "Working as guest.");
- }
- }
- return data;
- }
-
- /**
- * GET HTTP request. Do the request a second time if the user is not logged in
- *
- * @param uri
- * @param params
- * @param xContentType
- * @param my
- * @param addF
- * @return
- */
- public static String requestLogged(final String uri, final Parameters params, boolean xContentType, boolean my, boolean addF) {
- HttpResponse response = request(uri, params, xContentType, my, addF);
- String data = getResponseData(response);
-
- if (!Login.getLoginStatus(data)) {
- if (Login.login() == StatusCode.NO_ERROR) {
- response = request(uri, params, xContentType, my, addF);
- data = getResponseData(response);
- } else {
- Log.i(Settings.tag, "Working as guest.");
- }
- }
- return data;
- }
-
public static String urlencode_rfc3986(String text) {
return StringUtils.replace(URLEncoder.encode(text).replace("+", "%20"), "%7E", "~");
}