Let's apply some oops concepts here
Have an HttpCommunication class that will only execute a request to send a request and receive a response from the server. Sample code that looks like this
package com.example.sample; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; 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.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; public class HttpCommunication { public String makeHttpRequest( String url, HttpMethods method, ArrayList< NameValuePair > requestParams, ArrayList< NameValuePair > postData ) throws Exception { InputStream inputStream = null; String response = ""; HttpParams httpParameters = new BasicHttpParams( ); int timeoutConnection = 15000; HttpConnectionParams.setConnectionTimeout( httpParameters, timeoutConnection ); int timeoutSocket = 15000; HttpConnectionParams.setSoTimeout( httpParameters, timeoutSocket ); DefaultHttpClient httpClient = new DefaultHttpClient( httpParameters ); if ( method == HttpMethods.POST ) { HttpPost httpPost = new HttpPost( url ); if ( requestParams != null && requestParams.size( ) > 0 ) { httpPost.setEntity( new UrlEncodedFormEntity( requestParams ) ); } HttpResponse httpResponse = httpClient.execute( httpPost ); HttpEntity httpEntity = httpResponse.getEntity( ); inputStream = httpEntity.getContent( ); } else if ( method == HttpMethods.GET ) { if ( requestParams != null && requestParams.size( ) > 0 ) { String paramString = URLEncodedUtils.format( requestParams, "utf-8" ); url += "?" + paramString; } HttpGet httpGet = new HttpGet( url ); HttpResponse httpResponse = httpClient.execute( httpGet ); HttpEntity httpEntity = httpResponse.getEntity( ); inputStream = httpEntity.getContent( ); } BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream, "UTF-8" ) ); StringBuilder sb = new StringBuilder( ); String line = null; while ( ( line = reader.readLine( ) ) != null ) { sb.append( line + "\n" ); } inputStream.close( ); response = sb.toString( ); return response; } }
Have an abstract base class that will act as a template for all the major web services in your application. This class will use the HttpCommunication class above to send the request. Requests will be sent from AsyncTask, therefore, they are completely asynchronous. The class will provide abstract methods that derived classes must override and provide definitions for.
1. getUrl () - Well-formatted request URL 2. getHttpMethod () - one of the HTTP methods from GET, POST, PUT, DELETE, PATCH
3. getRequestParams () - Request parameters (headers), if any.
4. getPostParams () - Message parameters, if any.
5. parseResponse (String) - derived classes should give a definition of this method to analyze the received response.
6. notifyError (int) - derived classes must define this method to handle the error that can be received during communication.
package com.example.sample; import java.util.ArrayList; import org.apache.http.NameValuePair; import android.os.AsyncTask; public abstract class BaseService { protected abstract String getUrl(); protected abstract HttpMethods getHttpMethod(); protected abstract ArrayList< NameValuePair > getRequestParams(); protected abstract ArrayList< NameValuePair > getPostParams(); protected abstract void parseResponse( String response ); protected abstract void notifyError( int errorCode ); public void send() { SendRequestTask sendRequestTask = new SendRequestTask( ); sendRequestTask.execute( ); } private class SendRequestTask extends AsyncTask< Void, Void, Integer > { @Override protected Integer doInBackground( Void... params ) { try { String url = getUrl( ); HttpMethods method = getHttpMethod( ); ArrayList< NameValuePair > httpParams = getRequestParams( ); ArrayList< NameValuePair > postParams = getPostParams( ); HttpCommunication httpCommunication = new HttpCommunication( ); String response = httpCommunication.makeHttpRequest( url, method, httpParams, postParams ); parseResponse( response ); } catch ( Exception ex ) { ex.printStackTrace( ); notifyError( CommunicationError.ERROR_COMMUNICATION ); } return 0; } } }
Here is the code for an example of the webservice class, which is derived from the above class;
package com.example.sample; import java.util.ArrayList; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; public class SignIn extends BaseService { private final String _emailId; private final String _password; private final String _signinUrl = "http://www.example.com/login.php"; public SignIn( String userName, String password ) { _emailId = userName; _password = null; } @Override protected String getUrl() { return _signinUrl; } @Override protected ArrayList< NameValuePair > getRequestParams() { ArrayList< NameValuePair > params = new ArrayList< NameValuePair >( ); params.add( new BasicNameValuePair( "header1", "header1" ) ); params.add( new BasicNameValuePair( "header2", "header2" ) ); return params; } @Override protected ArrayList< NameValuePair > getPostParams() { ArrayList< NameValuePair > params = new ArrayList< NameValuePair >( ); params.add( new BasicNameValuePair( "email", _emailId ) ); params.add( new BasicNameValuePair( "password", _password ) ); return params; } @Override protected HttpMethods getHttpMethod() { return HttpMethods.POST; } @Override protected void parseResponse( String response ) {
Here's how you can use the SignIn web service;
SignIn signIn = new SignIn(" abic@gmail.com ", "abc123"); signIn.send();
Modify your HttpCommunication class as follows.
package com.example.sample; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import org.apache.http.NameValuePair; public class HttpCommunication { private final int CONNECTION_TIMEOUT = 10 * 1000; public HttpCommunication() { } public String makeHttpRequest( String strUrl, HttpMethods method, ArrayList< NameValuePair > requestParams, ArrayList< NameValuePair > postData ) throws Exception { HttpURLConnection connection = null; InputStream inputStream = null; URL url = null; String response = null; try { url = new URL( strUrl ); connection = (HttpURLConnection) url.openConnection( ); connection.setConnectTimeout( CONNECTION_TIMEOUT ); connection.setReadTimeout( CONNECTION_TIMEOUT ); if ( requestParams != null && requestParams.size( ) > 0 ) { for ( NameValuePair pair : requestParams ) { connection.setRequestProperty( pair.getName( ), pair.getValue( ) ); } } connection.setDoInput( true ); connection.connect( ); if ( method == HttpMethods.POST ) { OutputStream os = connection.getOutputStream( );