Http/Https connection is necessary to build a Android application for interact with web server.
To make http connection, I made 2 simple java classes.
It is working well and tested on android SDK 15 version and it will probably work the other version as well. I hope it can save your time.
You can call "doPostRequestNgetResponseBody" method or similar in your android Activity class. you can find more method from "HttpClientUtil" class.
String url = "https://yoursite";
ArrayList<BasicNameValuePair> arrayList = new ArrayList<BasicNameValuePair>();
arrayList.add(new BasicNameValuePair("your param name", "your param value"));
String responseBody = HttpRequestUtil.doPostRequestNgetResponseBody(context, url, arrayList);
To call the method, you need to have below 2 classes.
HttpClientUtil.java : return http/https connection client.
package com.jackapps.http;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import android.content.Context;
import android.net.SSLCertificateSocketFactory;
import android.net.SSLSessionCache;
public class HttpClientUtil {
private static final int CONNECTION_TIMEOUT = 5000;
private static final int SOCKET_TIMEOUT = 20000;
/**
* @param context
* @return
*/
static HttpClient getHttpClient(Context context) {
return getHttpClient(context, CONNECTION_TIMEOUT, SOCKET_TIMEOUT);
}
/**
* @param context
* @param connectionTimeOut
* @param sockeTimeOut
* @return
*/
static synchronized HttpClient getHttpClient(Context context, int connectionTimeOut, int sockeTimeOut) {
// Use a session cache for SSL sockets
SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context);
// sets up parameters
HttpParams httpParams = new BasicHttpParams();
setHttpProtocolParams(httpParams);
setHttpConnectionParams(httpParams, connectionTimeOut, sockeTimeOut);
httpParams.setBooleanParameter("http.protocol.expect-continue", false);
// registers schemes for both http and https
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
final SSLSocketFactory sslSocketFactory = SSLCertificateSocketFactory.getHttpSocketFactory(sockeTimeOut,
sessionCache);
// sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registry.register(new Scheme("https", sslSocketFactory, 443));
ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(httpParams, registry);
return new DefaultHttpClient(manager, httpParams);
}
/**
* @param httpParams
*/
private static void setHttpProtocolParams(HttpParams httpParams){
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(httpParams, "utf-8");
}
/**
* @param httpParams
* @param connectionTimeOut
* @param sockeTimeOut
*/
private static void setHttpConnectionParams(HttpParams httpParams, int connectionTimeOut, int sockeTimeOut){
HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeOut);
HttpConnectionParams.setSoTimeout(httpParams, sockeTimeOut);
}
}
HttpRequestUtil.java : return response body, headers
package com.jackapps.http;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import android.content.Context;
import com.jackapps.model.AccessTokenInfo;
public class HttpRequestUtil {
/**
* @param context
* @param url
* @param headerList
* @return
*/
public static String doGetRequestNgetResponseBody(Context context, String url, List headerList) {
URI uri = null;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
e.printStackTrace();
}
HttpGet get = new HttpGet(uri);
for (Header header : headerList) {
get.addHeader(header);
}
return getResponseBody(context, get);
}
/**
* @param context
* @param url
* @param headerList
* @return
*/
public static HttpResponse doGetRequestNgetResponse(Context context, String url, List headerList) {
URI uri = null;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
e.printStackTrace();
}
HttpGet get = new HttpGet(uri);
for (Header header : headerList) {
get.addHeader(header);
}
return getResponse(context, get);
}
/**
* @param context
* @param url
* @param params
* @return
*/
public static String doPostRequestNgetResponseBody(Context context, String url, List params) {
HttpPost post = new HttpPost(url);
UrlEncodedFormEntity ent = null;
try {
ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (ent != null)
post.setEntity(ent);
return getResponseBody(context, post);
}
/**
* @param context
* @param url
* @param params
* @return
*/
public static HttpResponse doPostRequestNgetResponse(Context context, String url, List params) {
HttpPost post = new HttpPost(url);
UrlEncodedFormEntity ent = null;
try {
ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (ent != null)
post.setEntity(ent);
return getResponse(context, post);
}
/**
* @param context
* @param url
* @param jsonParams
* @return
*/
public static String doPostRequestNgetResponseBody(Context context, String url, JSONObject jsonParams) {
HttpPost post = new HttpPost(url);
StringEntity ent = null;
try {
ent = new StringEntity(jsonParams.toString(), HTTP.UTF_8);
ent.setContentType("application/json");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (ent != null)
post.setEntity(ent);
return getResponseBody(context, post);
}
/**
* @param context
* @param url
* @param jsonParams
* @return
*/
public static HttpResponse doPostRequestNgetResponse(Context context, String url, JSONObject jsonParams) {
HttpPost post = new HttpPost(url);
StringEntity ent = null;
try {
ent = new StringEntity(jsonParams.toString(), HTTP.UTF_8);
ent.setContentType("application/json");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (ent != null)
post.setEntity(ent);
return getResponse(context, post);
}
/**
* @param context
* @param httpRequest
* @return
*/
private static String getResponseBody(Context context, HttpRequestBase httpRequest) {
HttpResponse response = getResponse( context, httpRequest);
return getResponseBody(response);
}
/**
* It returns response body string
* @param response
* @return
*/
public static String getResponseBody(HttpResponse response) {
HttpEntity resEntity = null;
if (response != null)
resEntity = response.getEntity();
if (resEntity != null) {
try {
return EntityUtils.toString(resEntity);
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
/**
* @param context
* @param url
* @param headerList
* @return
*/
public static HashMap doGetRequestNgetResponseHeader(Context context, String url, List headerList) {
URI uri = null;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
e.printStackTrace();
}
HttpGet get = new HttpGet(uri);
for (Header header : headerList) {
get.addHeader(header);
}
return getResponseHeader(context, get);
}
/**
* @param context
* @param url
* @param params
* @return
*/
public static HashMap doPostRequestNgetResponseHeader(Context context, String url, List params) {
HttpPost post = new HttpPost(url);
UrlEncodedFormEntity ent = null;
try {
ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (ent != null)
post.setEntity(ent);
return getResponseHeader(context, post);
}
/**
* @param context
* @param url
* @param jsonParams
* @return
*/
public static HashMap doPostRequestNgetResponseHeader(Context context, String url, JSONObject jsonParams) {
HttpPost post = new HttpPost(url);
StringEntity ent = null;
try {
ent = new StringEntity(jsonParams.toString(), HTTP.UTF_8);
ent.setContentType("application/json");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (ent != null)
post.setEntity(ent);
return getResponseHeader(context, post);
}
/**
* @param context
* @param httpRequest
* @return
*/
private static HashMap getResponseHeader(Context context, HttpRequestBase httpRequest) {
HttpResponse response = getResponse( context, httpRequest);
return getResponseHeader(response);
}
/**
* @param response
* @param headerName
* @return
*/
public static String getResponseHeaderValue(HttpResponse response, String headerName){
HashMap header = getResponseHeader(response);
return (String)header.get(headerName);
}
/**
* @param response
* @return
*/
public static HashMap getResponseHeader(HttpResponse response) {
if (response != null){
Header[] headers = response.getAllHeaders();
return converHeaders2Map(headers);
}else{
return new HashMap();
}
}
/**
* when response parameter is null, it will return 410 Gone status.
* @param response
* @return
*/
public static int getResponseCode(HttpResponse response) {
if (response != null){
return response.getStatusLine().getStatusCode();
}else{
return HttpStatus.SC_GONE;
}
}
/**
* @param headers
* @return
*/
private static HashMap converHeaders2Map(Header[] headers){
HashMap hashMap = new HashMap();
for(Header header: headers){
hashMap.put(header.getName(), header.getValue());
}
return hashMap;
}
/**
* @param context
* @param httpRequest
* @return
*/
public static HttpResponse getResponse(Context context, HttpRequestBase httpRequest) {
HttpClient httpClient = HttpClientUtil.getHttpClient(context);
HttpResponse response = null;
try {
response = httpClient.execute(httpRequest);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return response;
}
}