0% found this document useful (0 votes)
179 views8 pages

Request and Response Handler

This document defines an OpayRequestHandler class that handles sending requests and receiving responses from an Opay API. It includes methods for sending application requests, getting an HTTP client based on the authentication mode, converting input streams to strings, managing cookies, and loading keystores for secure connections. The class uses Apache HTTP client libraries to make requests and handles responses asynchronously via a callback listener.

Uploaded by

Ananya Vastav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
179 views8 pages

Request and Response Handler

This document defines an OpayRequestHandler class that handles sending requests and receiving responses from an Opay API. It includes methods for sending application requests, getting an HTTP client based on the authentication mode, converting input streams to strings, managing cookies, and loading keystores for secure connections. The class uses Apache HTTP client libraries to make requests and handles responses asynchronously via a callback listener.

Uploaded by

Ananya Vastav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 8

package com.ondot.opayservice.

http;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import

java.io.BufferedReader;
java.io.IOException;
java.io.InputStream;
java.io.InputStreamReader;
java.net.ConnectException;
java.net.CookieManager;
java.net.HttpCookie;
java.net.Socket;
java.net.UnknownHostException;
java.security.KeyManagementException;
java.security.KeyStore;
java.security.KeyStoreException;
java.security.NoSuchAlgorithmException;
java.security.UnrecoverableKeyException;
java.security.cert.CertificateException;
java.security.cert.X509Certificate;
java.util.List;
java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import

org.apache.http.HttpResponse;
org.apache.http.HttpVersion;
org.apache.http.client.HttpClient;
org.apache.http.client.ResponseHandler;
org.apache.http.client.methods.HttpPost;
org.apache.http.conn.ClientConnectionManager;
org.apache.http.conn.scheme.PlainSocketFactory;
org.apache.http.conn.scheme.Scheme;
org.apache.http.conn.scheme.SchemeRegistry;
org.apache.http.conn.ssl.SSLSocketFactory;
org.apache.http.conn.ssl.X509HostnameVerifier;
org.apache.http.entity.StringEntity;
org.apache.http.impl.client.BasicResponseHandler;
org.apache.http.impl.client.DefaultHttpClient;
org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
org.apache.http.params.BasicHttpParams;
org.apache.http.params.HttpParams;
org.apache.http.params.HttpProtocolParams;
org.apache.http.protocol.HTTP;
org.json.JSONException;
org.json.JSONObject;
org.json.simple.JSONValue;

import
import
import
import
import

android.content.Context;
android.content.SharedPreferences;
android.net.ConnectivityManager;
android.net.NetworkInfo;
android.util.Log;

import com.android.volley.RequestQueue;
import com.ondot.opayservice.OpayShowAlertDialog;
import com.ondot.opayservice.R;
public class OpayRequestHandler {

//

/**
* @uml.property name="requestQueue"
* @uml.associationEnd readOnly="true"
*/
RequestQueue requestQueue;
private final static String schemeSSL = "https";
/**
* @uml.property name="sslPort"
*/
private final int sslPort = 443;
private final int sslPort = 27001;
private final static String ksp = "ondot1234";
private final static String keystoreType = "BKS";
/**
* @uml.property name="listener"
* @uml.associationEnd
*/
OpayResponseListener listener;
static OpayRequestHandler requestHandler;
/**
* @uml.property name="_context"
* @uml.associationEnd
*/
Context _context;
public OpayRequestHandler() {
}
public static OpayRequestHandler getSingltonObject() {
if (requestHandler == null)
requestHandler = new OpayRequestHandler();
return requestHandler;
}
protected static final String TYPE_UTF8_CHARSET = "charset=UTF-8";

public void sendApplicationRequest(String requestUrl, final Map<String,


Object> params, OpayResponseListener opayResponseListener, final Context context
) {
_context = context;
ConnectivityManager connMgr = (ConnectivityManager) context.get
SystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()) {
try {
this.listener = opayResponseListener;
final String url = requestUrl;
final HttpClient httpClient = getHttpClientBased
OnAuthMode(1,context);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
HttpPost httpPost = new

HttpPost(url);
String json = "";
InputStream inputStream
= null;
String result = "";
String values = JSONValu
e.toJSONString(params);
JSONObject postData = nu
ll;
try {
postData = new J
SONObject(values);
} catch (JSONException e
1) {
e1.printStackTra
ce();
}
json = postData.toString
();
StringEntity se = new St
ringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Acce
pt", "application/json");
httpPost.setHeader("Cont
ent-type", "application/json");
HttpResponse httpRespons
e = null;
//

Abitha commented
try {
httpResponse = httpClien

t.execute(httpPost);
} catch (Exception e) {
listener.onError
Received(e.toString());
}
inputStream = httpRespon
se.getEntity().getContent();
//Abitha
inputStream= httpPost.ge
tEntity().getContent();
result = convertInputStr
eamToString(inputStream);
//
responseHandler=new BasicResponseHandler();
//
.execute(httpPost, responseHandler);
//
ct(responseBody);

//ends
//Abitha added
ResponseHandler<String>
String responseBody = httpClient
JSONObject response=new JSONObje
//ends

if (inputStream != null)
{
result = convert
InputStreamToString(inputStream);
listener.onRespo
nseReceived(result);
}
} catch (Exception e) {
listener.onErrorReceived
(e.toString());
}
}
});
thread.start();
} catch (Exception e) {
listener.onErrorReceived(e.toString());
}
} else{
OpayShowAlertDialog.showAlertDialog(context, "O Pay","No
Internet Connection");
}
}
private static String convertInputStreamToString(InputStream inputStream
) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStre
amReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
// Required for Cookie Handling
/**
* @uml.property name="mCookieManager"
*/
public CookieManager mCookieManager = new CookieManager();
/**
* @uml.property name="cOOKIES_HEADER"
*/
String COOKIES_HEADER = "Set-Cookie";
/**
* @uml.property name="cOOKIE_KEY"
*/
String COOKIE_KEY = "Cookie";
static String ONDOT_SESSION_COOKIE = "ondotSessionId";
public List<HttpCookie> getCookie(Context context) {
List<HttpCookie> httpCookie = null;
if (mCookieManager.getCookieStore().getCookies().size() > 0) {
httpCookie = mCookieManager.getCookieStore().getCookies(
);
}
return httpCookie;

}
public static String getOndotCookie(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferenc
es("COOKIE", Context.MODE_PRIVATE);
return sharedPreferences.getString(ONDOT_SESSION_COOKIE, "");
}
public HttpClient getHttpClientBasedOnAuthMode(int mode, Context context
) throws Exception {
if (mode == 0) {
return new DefaultHttpClient();
} else if (mode == 1) {
return getHttpClientSSL();
} else if (mode == 2) {
return getHttpClientMutualAuth(context);
}
return null;
//
//
//
//
//
//
//
//
//
//
//
//
//
////

if (mode == 0) {
return new DefaultHttpClient();
} else if (mode == 1) {
HttpClient ht=getHttpClientSSL();
return ht;
} else if (mode == 2) {
return getHttpClientMutualAuth(context);
}
else
{
HttpClient ht=getHttpClientSSL();
return ht;
}
return null;
}

private HttpClient getHttpClientSSL() throws Exception {


try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getD
efaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore)
;
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNA
ME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1
_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8)
;
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme(schemeSSL, sf, sslPort));
ClientConnectionManager ccm = new ThreadSafeClientConnMa

nager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
throw new Exception(e);
}
}
class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgo
rithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyExcep
tion {
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();
}
}
private HttpClient getHttpClientMutualAuth(Context context) throws Excep
tion {
try {
final KeyStore truststore = loadStore(context.getResourc
es().openRawResource(R.raw.clienttruststore), null, keystoreType);
final KeyStore keystore = loadStore(context.getResources
().openRawResource(R.raw.client), ksp, keystoreType);
SSLSocketFactory sf = createFactory(keystore, ksp, trust
store);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNA
ME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1
_1);

HttpProtocolParams.setContentCharset(params, HTTP.UTF_8)
;
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme(schemeSSL, sf, sslPort));
ClientConnectionManager ccm = new ThreadSafeClientConnMa
nager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
throw new Exception(e);
}
}
private SSLSocketFactory createFactory(final KeyStore keystore, final St
ring keystorePassword, final KeyStore truststore) {
SSLSocketFactory factory;
try {
factory = new SSLSocketFactory(keystore, keystorePasswor
d, truststore);
factory.setHostnameVerifier((X509HostnameVerifier) SSLSo
cketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
} catch (Exception e) {
throw new RuntimeException(e);
}
return factory;
}
/* Loads keystore for SSL connection */
private KeyStore loadStore(InputStream stream, String keystorePw, String
type) throws Exception {
KeyStore keyStore;
try {
keyStore = KeyStore.getInstance(type);
if (keystorePw != null && keystorePw.length() > 0)
keyStore.load(stream, keystorePw.toCharArray());
else
keyStore.load(stream, null);
} finally {
stream.close();
}
return keyStore;
}
public boolean isConnectedToInternet(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.St
ate.CONNECTED) {
return true;
}
}
return false;

}
}

You might also like