Created
October 7, 2014 14:40
-
-
Save alxsimo/fbd39f5b6cc04d0e4237 to your computer and use it in GitHub Desktop.
[Java] Custom HTTP Client (Apache) with cookies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package es.ineco.sima.helper.network; | |
/** | |
* Created by alexandru.simonescu on 29/09/2014. | |
*/ | |
import android.content.Context; | |
import android.util.Log; | |
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.net.URI; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
import org.apache.http.Header; | |
import org.apache.http.HttpResponse; | |
import org.apache.http.NameValuePair; | |
import org.apache.http.client.CookieStore; | |
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.conn.params.ConnManagerParams; | |
import org.apache.http.cookie.Cookie; | |
import org.apache.http.impl.client.BasicCookieStore; | |
import org.apache.http.impl.client.DefaultHttpClient; | |
import org.apache.http.params.CoreProtocolPNames; | |
import org.apache.http.params.HttpConnectionParams; | |
import org.apache.http.params.HttpParams; | |
public class CustomHttpClient { | |
public static int httpRequestStatusCode = 000; | |
private static final String TAG = CustomHttpClient.class.getSimpleName(); | |
/** The time it takes for our client to timeout */ | |
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds | |
/** Single instance of our HttpClient */ | |
private static DefaultHttpClient mHttpClient; | |
/** | |
* Get our single instance of our HttpClient object. | |
* | |
* @return an HttpClient object with connection parameters set | |
*/ | |
private static DefaultHttpClient getHttpClient() { | |
if (mHttpClient == null) { | |
mHttpClient = new DefaultHttpClient(); | |
final HttpParams params = mHttpClient.getParams(); | |
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT); | |
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT); | |
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT); | |
} | |
return mHttpClient; | |
} | |
/** | |
* Performs an HTTP Post request to the specified url with the | |
* specified parameters. | |
* | |
* @param url The web address to post the request to | |
* @param postParameters The parameters to send via the request | |
* @return The result of the request | |
* @throws Exception | |
*/ | |
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters, Context ctx, boolean persistResponseCookies) throws Exception { | |
BufferedReader in = null; | |
try { | |
DefaultHttpClient client = getHttpClient(); | |
HttpPost request = new HttpPost(url); | |
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters); | |
Log.d(TAG, Arrays.toString(postParameters.toArray())); | |
request.setEntity(formEntity); | |
HttpResponse response = client.execute(request); | |
httpRequestStatusCode = response.getStatusLine().getStatusCode(); | |
System.out.println("Response Status Code: "+httpRequestStatusCode); | |
if (persistResponseCookies) { | |
List<Cookie> cookies = client.getCookieStore().getCookies(); | |
// Persistir en SharedPreferences | |
CookieHelper ckh = new CookieHelper(ctx); | |
ckh.saveSharedPreferencesCookies(cookies); | |
// Listar cookies -- TODO obtener desde SharedPreferences | |
Header[] headers = response.getHeaders("Set-Cookie"); | |
for (Header h : headers) { | |
System.out.println("COOKIE: " + h.getValue().toString()); | |
} | |
} | |
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); | |
StringBuffer sb = new StringBuffer(""); | |
String line = ""; | |
String NL = System.getProperty("line.separator"); | |
while ((line = in.readLine()) != null) { | |
sb.append(line + NL); | |
} | |
in.close(); | |
String result = sb.toString(); | |
return result; | |
} finally { | |
if (in != null) { | |
try { | |
in.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
/** | |
* Performs an HTTP GET request to the specified url. | |
* | |
* @param url The web address to post the request to | |
* @param useSessionCookies Uses cookies persisted in | |
* SharedPreferences | |
* @return The result of the request | |
* @throws Exception | |
*/ | |
public static String executeHttpGet(String url, Context ctx, boolean useSessionCookies) throws Exception { | |
BufferedReader in = null; | |
try { | |
DefaultHttpClient client = getHttpClient(); | |
HttpGet request = new HttpGet(); | |
request.setHeader(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); | |
request.setURI(new URI(url)); | |
// "Inyecta" cookie en el cliente | |
if (useSessionCookies) { | |
CookieHelper ch = new CookieHelper(ctx); | |
List<Cookie> cookies = ch.loadSharedPreferencesCookie(); | |
if (cookies != null) { | |
CookieStore cookieStore = new BasicCookieStore(); | |
for (int i=0; i<cookies.size(); i++) | |
cookieStore.addCookie(cookies.get(i)); | |
client.setCookieStore(cookieStore); | |
} | |
/* | |
HttpResponse response = client.execute(httpPost); | |
cookies = client.getCookieStore().getCookies(); | |
saveSharedPreferencesCookies(cookies); | |
*/ | |
} | |
HttpResponse response = client.execute(request); | |
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); | |
StringBuffer sb = new StringBuffer(""); | |
String line = ""; | |
String NL = System.getProperty("line.separator"); | |
while ((line = in.readLine()) != null) { | |
sb.append(line + NL); | |
} | |
in.close(); | |
String result = sb.toString(); | |
return result; | |
} finally { | |
if (in != null) { | |
try { | |
in.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment