Integrating HTTP and HTTPS Connection - CodeProject
Integrating HTTP and HTTPS Connection - CodeProject
In this article I have discussed the procedure to request HTTP and HTTPS requests in android.
Introduction
In this article I have discussed the procedure to request HTTP and HTTPS requests in android. In mobiles, most of applications
based on client server communication through HTTP or HTTPS protocol, so it is
essential for a small or a large sized application that your HTTP module follows the complete object oriented and has a separate
coupled module from other package of application.
Focus in this article is that an only single class handles both types of request (HTTP and HTTPS), normally developers handle the
HTTP and HTTPS in two different classes, but in this in potent interest, I have handled it in a single class. Developer will need to
invoke a class and implement a listener for getting the response as a notification.
Background
Steps involved:
requestParameter .add(namVaulePair);
1 of 14 6/7/2018 9:59 AM
Integrating HTTP and HTTPS Connection - CodeProject https://www.codeproject.com/Articles/396027/Integrating-HTTP-and...
requestParameters: if request method types is ‘POST’ then user set the list of parameters in form of NameValuePair
otherwise It should be null if request method type is ‘GET’.
header: it contain the header you want to set in each HTTP request.
reqId : unique identifier of HTTP request.
getResCode(): it return the HTTP status line. If return 200 then request is successful another wise it fail due to server reason.
Or invalid request by client.
addHTTPListener: add the concrete class which implement the HTTPListener class and override notifyResponse()
for handle response return by server.
package com.brickred.HTTP;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import org.apache.HTTP.HTTPEntity;
import org.apache.HTTP.HTTPResponse;
import org.apache.HTTP.HTTPVersion;
import org.apache.HTTP.NameValuePair;
import org.apache.HTTP.client.ClientProtocolException;
import org.apache.HTTP.client.HTTPClient;
import org.apache.HTTP.client.ResponseHandler;
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.ClientConnectionManager;
import org.apache.HTTP.conn.params.ConnManagerPNames;
import org.apache.HTTP.conn.params.ConnPerRouteBean;
import org.apache.HTTP.conn.scheme.PlainSocketFactory;
import org.apache.HTTP.conn.scheme.Scheme;
import org.apache.HTTP.conn.scheme.SchemeRegistry;
2 of 14 6/7/2018 9:59 AM
Integrating HTTP and HTTPS Connection - CodeProject https://www.codeproject.com/Articles/396027/Integrating-HTTP-and...
import org.apache.HTTP.entity.StringEntity;
import org.apache.HTTP.impl.client.DefaultHTTPClient;
import org.apache.HTTP.impl.conn.SingleClientConnManager;
import org.apache.HTTP.params.BasicHTTPParams;
import org.apache.HTTP.params.CoreConnectionPNames;
import org.apache.HTTP.params.HTTPParams;
import org.apache.HTTP.params.HTTPProtocolParams;
import org.apache.HTTP.util.EntityUtils;
import android.content.Context;
import android.util.Log;
/**
* url for example
HTTP://wwww.google.com
*/
/**
* past request parameter items
*/
String resMessage = "No Response Please check Url or it may be HTTPS certificate issue.";
/**
* response code
*/
/**
* @param urlstring
* requested url
* @param requestParameters
* list post parameters if get request then null
* @param header
* list of header
* @param reqId
* url request id
*/
public HTTPHandler(String urlstring,
final List<NameValuePair> requestParameters,
final Hashtable<String, String> header, int reqId) {
this.urlstring = urlstring;
this.postRequestParameters = requestParameters;
this.reqId = reqId;
this.header = header;
}
/**
* @return reqest id for request
3 of 14 6/7/2018 9:59 AM
Integrating HTTP and HTTPS Connection - CodeProject https://www.codeproject.com/Articles/396027/Integrating-HTTP-and...
*/
/**
* Return requested url
*
* @return
*/
public String getURL() {
return urlstring;
}
/**
* @return the response
*/
/**
* Return Response Code
*
* @return
*/
/**
* @param HTTPListener
* add the listener for notify the response
*/
/**
* send the HTTP or HTTPS request
*/
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 50000);
params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new
ConnPerRouteBean(30));
params.setParameter(HTTPProtocolParams.USE_EXPECT_CONTINUE, false);
HTTPProtocolParams.setVersion(params, HTTPVersion.HTTP_1_1);
ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);
4 of 14 6/7/2018 9:59 AM
Integrating HTTP and HTTPS Connection - CodeProject https://www.codeproject.com/Articles/396027/Integrating-HTTP-and...
if (header != null) {
Enumeration enums = header.keys();
while (enums.hasMoreElements()) {
String key = (String) enums.nextElement();
String value = header.get(key);
HTTPpost.addHeader(key, value);
}
}
HTTPpost.setEntity(new UrlEncodedFormEntity(postRequestParameters));
// Response handler
ResponseHandler<String> reshandler = new ResponseHandler<String>() {
// invoked when client receives response
public String handleResponse(HTTPResponse response)
byte[] b = EntityUtils.toByteArray(entity);
// write the response byte array to a string buffer
out.append(new String(b, 0, b.length));
return out.toString();
}
};
byte[] b = EntityUtils.toByteArray(entity);
// write the response byte array to a string buffer
out.append(new String(b, 0, b.length));
return out.toString();
}
};
5 of 14 6/7/2018 9:59 AM
Integrating HTTP and HTTPS Connection - CodeProject https://www.codeproject.com/Articles/396027/Integrating-HTTP-and...
HTTPListener: This listener must be implement and override the single abstract method notifyResponse() for get the
response generated by HTTP request and know the status of request.
Code:
package com.brickred.HTTP;
/**
* @author ravindrap
* HTTPListener is super class of which set the HTTP or HTTPS request
*/
EasySSlSocketFactory: This socket factory class will create the self signed certificate.
Hide Shrink Copy Code
package com.testHTTPS;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* HTTP://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import org.apache.HTTP.conn.ConnectTimeoutException;
import org.apache.HTTP.conn.scheme.LayeredSocketFactory;
import org.apache.HTTP.conn.scheme.SocketFactory;
import org.apache.HTTP.params.HTTPConnectionParams;
import org.apache.HTTP.params.HTTPParams;
6 of 14 6/7/2018 9:59 AM
Integrating HTTP and HTTPS Connection - CodeProject https://www.codeproject.com/Articles/396027/Integrating-HTTP-and...
/**
* This socket factory will create ssl socket that accepts self signed
* certificate
*
* @author olamy
* @version $Id:
EasySSLSocketFactory.java 765355 2009-04-15 20:59:07Z evenisse
* $
* @since 1.2.3
*/
return this.sslcontext;
}
/**
* @see org.apache.HTTP.conn.scheme.SocketFactory#connectSocket(java.net.Socket,
* java.lang.String, int, java.net.InetAddress, int,
* org.apache.HTTP.params.HTTPParams)
*/
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int
localPort, HTTPParams params)
/**
* @see org.apache.HTTP.conn.scheme.SocketFactory#createSocket()
*/
7 of 14 6/7/2018 9:59 AM
Integrating HTTP and HTTPS Connection - CodeProject https://www.codeproject.com/Articles/396027/Integrating-HTTP-and...
/**
* @see org.apache.HTTP.conn.scheme.SocketFactory#isSecure(java.net.Socket)
*/
/**
* @see org.apache.HTTP.conn.scheme.LayeredSocketFactory#createSocket(java.net.Socket,
* java.lang.String, int, boolean)
*/
public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
throws IOException, UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);
//return getSSLContext().getSocketFactory().createSocket();
}
// -------------------------------------------------------------------
// javadoc in org.apache.HTTP.conn.scheme.SocketFactory says :
// Both Object.equals() and Object.hashCode() must be overridden
// for the correct operation of some connection managers
// -------------------------------------------------------------------
package com.brickred.HTTP;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* HTTP://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
8 of 14 6/7/2018 9:59 AM
Integrating HTTP and HTTPS Connection - CodeProject https://www.codeproject.com/Articles/396027/Integrating-HTTP-and...
/**
* @author olamy
* @version $Id:
EasyX509TrustManager.java 765355 2009-04-15 20:59:07Z evenisse $
* @since 1.2.3
*/
/**
* Constructor for EasyX509TrustManager.
*/
public EasyX509TrustManager( KeyStore keystore )
throws NoSuchAlgorithmException, KeyStoreException
{
super();
TrustManagerFactory factory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm() );
factory.init( keystore );
TrustManager[] trustmanagers = factory.getTrustManagers();
if ( trustmanagers.length == 0 )
{
throw new NoSuchAlgorithmException( "no trust manager found" );
}
this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}
/**
* @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String authType)
*/
throws CertificateException
{
standardTrustManager.checkClientTrusted( certificates, authType );
}
/**
* @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType)
*/
public void checkServerTrusted(X509Certificate[] certificates, String authType )
throws CertificateException
{
if ( ( certificates != null) && ( certificates.length == 1 ) )
{
certificates[0].checkValidity();
}
else
{
standardTrustManager.checkServerTrusted( certificates, authType );
}
}
/**
* @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
*/
AndroidManifest.xml
Hide Copy Code
9 of 14 6/7/2018 9:59 AM
Integrating HTTP and HTTPS Connection - CodeProject https://www.codeproject.com/Articles/396027/Integrating-HTTP-and...
package="com.brickred"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
HTTPConnectionApiActivity.java
package com.brickred.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.brickred.R;
import com.brickred.HTTP.HTTPHandler;
import com.brickred.HTTP.HTTPListner;
buttonClickMe.setOnClickListener(new OnClickListener() {
10 of 14 6/7/2018 9:59 AM
Integrating HTTP and HTTPS Connection - CodeProject https://www.codeproject.com/Articles/396027/Integrating-HTTP-and...
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Log.i("", msg)
if(edtTextUrl.getText().length() > 0 && edtTextUrl.getText().toString().startsWith("HTTP")){
progressDialog.setMessage("Please wait for response ... ");
progressDialog.show();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
HTTPHandler handler = new HTTPHandler(edtTextUrl.getText().toString().trim(),null, null, 123);
handler.addHTTPLisner(HTTPConnectionApiActivity.this);
handler.sendRequest();
}
}).start();
}else{
showAlert("Error", "Please enter valid url", null, "Ok");
}
}
});
}
@Override
public void notifyHTTPRespons(final HTTPHandler HTTP) {
// TODO Auto-generated method stub
progressDialog.cancel();
Log.i("Log", "responce == "+HTTP.getResCode());
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
textviewResponse.setText("");
textviewResponse.setText(HTTP.getResponse());
}
});
}
/**
* @param title
* @param Message
* @param NegButton
* @param posButton
*/
private void showAlert(String title,String Message, final String NegButton,
final String posButton) {
}
});
}
if (posButton != null) {
alertBuilder.setPositiveButton(posButton,
new DialogInterface.OnClickListener() {
11 of 14 6/7/2018 9:59 AM
Integrating HTTP and HTTPS Connection - CodeProject https://www.codeproject.com/Articles/396027/Integrating-HTTP-and...
}
});
}
AlertDialog alert = alertBuilder.create();
alert.show();
}
}
Points of Interest
Interesting point in this article is user no need to write a difference code for HTTP and HTTPS protocol. User need only just enter
the the URL as per as his/her requirement and send the request and its works on multithreading environment. User can
send multiple request at that same time without waiting the previous request completion.
License
This article, along with any associated source code and files, is
licensed under The Code Project Open License (CPOL)
Share
TWITTER FACEBOOK
No Biography provided
12 of 14 6/7/2018 9:59 AM
Integrating HTTP and HTTPS Connection - CodeProject https://www.codeproject.com/Articles/396027/Integrating-HTTP-and...
Search Comments
Sign In · View Thread
Sign In · View Thread
Good work. Although there are a few spelling mistakes in the code (no big deal). Here's a 5 and keep up the good
work.
Sign In · View Thread
Sign In · View Thread
13 of 14 6/7/2018 9:59 AM
Integrating HTTP and HTTPS Connection - CodeProject https://www.codeproject.com/Articles/396027/Integrating-HTTP-and...
Sign In · View Thread
Sign In · View Thread
Hi,
I think you have forgotten to include the download link for the zip file of the project.
Recently, I have to do this stuff while making the docs of a project of mine. I discovered how helpful is, as an example,
to include a simple file upload and download service using https, with all the EasySSlSocketFactory and
EasyX509TrustManager code as you explain in the article. But also including the simple backend php script to give
feedback of the result of the transfers and moving files to the correspondant directory in the remote server. If you are
interested in extend this article or make another, as a sequel of this, I can provide working code for this. We use this
method as an easy way to make remote updates of the additional app supporting data.
Although you can get this information on several sites on the net I think you made a great work putting all together in
this article. Don't we all love Codeproject articles ? Here you get all you need together in one place.
Good work.
Sign In · View Thread
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile Layout: fixed | Article Copyright 2012 by Ravindra Kumar Prajapati
Web01 | 2.8.180605.1 | Last Updated 6 Jun 2012 fluid Everything else Copyright © CodeProject, 1999-2018
14 of 14 6/7/2018 9:59 AM