/* * sends the json object to sever */ public JSONObject SendHttpPost(JSONObject jsonObjSend) throws Throwable { DefaultHttpClient httpclient = null; try { httpclient = getClient();//new DefaultHttpClient(); HttpParams params = httpclient.getParams(); //HttpConnectionParams.setConnectionTimeout(params, 90000); HttpConnectionParams.setSoTimeout(params,90000); HttpPost httpPostRequest = new HttpPost(URL); StringEntity se; se = new StringEntity(jsonObjSend.toString(), "UTF-8"); // Set HTTP parameters httpPostRequest.setEntity(se); httpPostRequest.setHeader("Connection", "Keep-Alive"); httpPostRequest.setHeader("Content-type", "text/plain");
Header[] headers = httpPostRequest.getAllHeaders(); for (int i = 0; i < headers.length; i++ ) { String name = headers[i].getName(); String value = headers[i].getValue(); System.out.println (name + " = " + value + " \n"); } BasicResponseHandler handler = new BasicResponseHandler(); //HttpResponse response = httpclient.execute(httpPostRequest); String response = (String) httpclient.execute(httpPostRequest,handler); System.out.println("The response is \n" + response); try { responseinjson = new JSONObject(response); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new JSONException(e.getMessage()); } //System.out.println("The response object is " + responseinjson + "\n"); }catch (java.net.ConnectException ce) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. ce.printStackTrace(); throw new ServerDataException("ConnectException"); } catch (java.net.SocketTimeoutException st) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. st.printStackTrace(); throw new ServerDataException("timed out"); } catch (java.net.SocketException se) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. se.printStackTrace(); throw new ServerDataException("timed out"); } catch (javax.net.ssl.SSLException sl) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. sl.printStackTrace(); throw new ServerDataException("timed out"); } catch (org.apache.http.conn.ConnectTimeoutException ct) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. ct.printStackTrace(); throw new ServerDataException("timed out"); } catch (java.net.UnknownHostException un) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. un.printStackTrace(); throw new ServerDataException("timed out"); } catch (org.apache.http.client.HttpResponseException ape) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. ape.printStackTrace(); throw new ServerDataException("timed out"); }
catch (Throwable t) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. t.printStackTrace(); throw t; } finally { httpclient.getConnectionManager().shutdown(); httpclient = null; } return responseinjson; }
/* * gets the stack trace in a string format to upload to Flurry */ public static String getStackTrace(Throwable aThrowable) { final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); aThrowable.printStackTrace(printWriter); return result.toString(); }
/* * gets the http client with allowing all host names for https protocol * */ private DefaultHttpClient getClient() { BasicHttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 60000); HttpConnectionParams.setSoTimeout(httpParameters, 60000); DefaultHttpClient client; // registers schemes for both http and httpsb SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); KeyStore trustStore; SSLSocketFactory sslSocketFactory; try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); sslSocketFactory = new MySSLSocketFactory(trustStore); } catch (Exception e) { e.printStackTrace(); sslSocketFactory = SSLSocketFactory.getSocketFactory(); } sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); registry.register(new Scheme("https", sslSocketFactory, 443)); ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(httpParameters, registry); client = new DefaultHttpClient(manager, httpParameters); //client.setHttpRequestRetryHandler(new HttpRequestRetryHandler()); return client; }
/* * Custom SSL Socket Factory */ class MySSLSocketFactory extends SSLSocketFactory { SSLContext sslContext = SSLContext.getInstance("TLS"); public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; sslContext.init(null, new TrustManager[] { tm }, null); } @Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); } @Override public Socket createSocket() throws IOException { return sslContext.getSocketFactory().createSocket(); } }
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;import com.ccas.roadsideconnect.exceptions.ServerDataException;
import com.ccas.roadsideconnect.utilities.RoadsideConnect;import org.apache.http.Header;
import org.apache.http.client.methods.HttpPost;
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.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
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.json.JSONException;
import org.json.JSONObject;
import android.content.Context;public class HTTPClient implements RoadsideConnect {
private static final String TAG = "HttpClient";
static Context context;
static JSONObject responseinjson;
/*
* sends the json object to sever
*/
public JSONObject SendHttpPost(JSONObject jsonObjSend) throws Throwable
{
DefaultHttpClient httpclient = null;
try
{
httpclient = getClient();//new DefaultHttpClient();
HttpParams params = httpclient.getParams();
//HttpConnectionParams.setConnectionTimeout(params, 90000);
HttpConnectionParams.setSoTimeout(params,90000);
HttpPost httpPostRequest = new HttpPost(URL);
StringEntity se;
se = new StringEntity(jsonObjSend.toString(), "UTF-8");
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Connection", "Keep-Alive");
httpPostRequest.setHeader("Content-type", "text/plain");
Header[] headers = httpPostRequest.getAllHeaders();
for (int i = 0; i < headers.length; i++ )
{
String name = headers[i].getName();
String value = headers[i].getValue();
System.out.println (name + " = " + value + " \n");
}
BasicResponseHandler handler = new BasicResponseHandler();
//HttpResponse response = httpclient.execute(httpPostRequest);
String response = (String) httpclient.execute(httpPostRequest,handler);
System.out.println("The response is \n" + response);
try
{
responseinjson = new JSONObject(response);
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
throw new JSONException(e.getMessage());
}
//System.out.println("The response object is " + responseinjson + "\n");
}catch (java.net.ConnectException ce)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
ce.printStackTrace();
throw new ServerDataException("ConnectException");
}
catch (java.net.SocketTimeoutException st)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
st.printStackTrace();
throw new ServerDataException("timed out");
}
catch (java.net.SocketException se)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
se.printStackTrace();
throw new ServerDataException("timed out");
}
catch (javax.net.ssl.SSLException sl)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
sl.printStackTrace();
throw new ServerDataException("timed out");
}
catch (org.apache.http.conn.ConnectTimeoutException ct)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
ct.printStackTrace();
throw new ServerDataException("timed out");
}
catch (java.net.UnknownHostException un)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
un.printStackTrace();
throw new ServerDataException("timed out");
}
catch (org.apache.http.client.HttpResponseException ape)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
ape.printStackTrace();
throw new ServerDataException("timed out");
}
catch (Throwable t)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
t.printStackTrace();
throw t;
} finally {
httpclient.getConnectionManager().shutdown();
httpclient = null;
}
return responseinjson;
}
/*
* gets the stack trace in a string format to upload to Flurry
*/
public static String getStackTrace(Throwable aThrowable) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
aThrowable.printStackTrace(printWriter);
return result.toString();
}
/*
* gets the http client with allowing all host names for https protocol
*
*/
private DefaultHttpClient getClient() {
BasicHttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 60000);
HttpConnectionParams.setSoTimeout(httpParameters, 60000);
DefaultHttpClient client; // registers schemes for both http and httpsb SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); KeyStore trustStore;
SSLSocketFactory sslSocketFactory;
try {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
sslSocketFactory = new MySSLSocketFactory(trustStore);
} catch (Exception e) {
e.printStackTrace();
sslSocketFactory = SSLSocketFactory.getSocketFactory();
} sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); registry.register(new Scheme("https", sslSocketFactory, 443)); ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(httpParameters,
registry); client = new DefaultHttpClient(manager, httpParameters);
//client.setHttpRequestRetryHandler(new HttpRequestRetryHandler());
return client;
}
/*
* Custom SSL Socket Factory
*/
class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS"); public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore); TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} public X509Certificate[] getAcceptedIssuers() {
return null;
}
}; sslContext.init(null, new TrustManager[] { tm }, null);
} @Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
} @Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
}
import org.json.JSONException;
import org.json.JSONObject;import android.util.Log;public class JSONResponseParser { /*
* Parse the JSON object for the Dispatch Job List
*/
JSONArray parseResponseDispatchJobList(JSONObject jsonToParse) { try {
JSONObject bodyreturned = (JSONObject) jsonToParse.get("Body");
JSONArray dispatchjoblist = bodyreturned
.getJSONArray("DispatchJobList");
Log.i("JobListResponse", dispatchjoblist.toString() + "");
return dispatchjoblist;
} catch (JSONException e) {
System.out.println("There was an error parsing SearchPOI Reponse!");
e.printStackTrace();
} return null;
} /*
* Parse the JSON object for the Login Response
*/
String parseLoginResponse(JSONObject jsonToParse) {
try {
JSONObject bodyreturned = (JSONObject) jsonToParse.get("Body");
String loginstatus = bodyreturned.getString("LoginStatus");
return loginstatus;
} catch (JSONException e) {
System.out.println("There was an error parsing SearchPOI Reponse!");
e.printStackTrace();
}
return null;
} String parseSignatureResponse(JSONObject jsonToParse) {
JSONObject bodyreturned;
try {
bodyreturned = (JSONObject) jsonToParse.get("Body");
String signatureID = bodyreturned.getString("SignatureID");
return signatureID;
} catch (JSONException e) {
e.printStackTrace();
} return null; } /*
* Parse the JSON object for the GPSLocation Response
*/ JSONObject parseGPSLocationResponse(JSONObject jsonToParse) {
try {
JSONObject bodyreturned = (JSONObject) jsonToParse.get("Body");
JSONObject locationstatus = bodyreturned
.getJSONObject("DispatchJobStatus");
return locationstatus; } catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/*
* Parse the JSON object for the Version Response
*/
String versionCheckResponse(JSONObject jsonToParse){
String versionstatus = "";
try {
JSONObject bodyreturned = (JSONObject) jsonToParse.get("Body");
versionstatus =((JSONObject)bodyreturned.get("ServiceResponse")).getBoolean("IsVersionValid")+"";
Log.i("versionresponse",versionstatus);
return versionstatus;
} catch (JSONException e) {
System.out.println("There was an error parsing versioncheck Reponse!");
e.printStackTrace();
}
return versionstatus;
}
String parseRegisterResponse (JSONObject jsonToParse){
JSONObject bodyreturned;
try {
bodyreturned = (JSONObject) jsonToParse.get("Body");
Log.i("registerresponse", bodyreturned.toString());
String registerStatus=bodyreturned.getString("ProfileID");
Log.i("registerResponse", registerStatus);
return registerStatus;
} catch (JSONException e) {
System.out.println("There was an error parsing register Reponse!");
e.printStackTrace();
}
return null;
}
}