ael.com.loterias.Library.c_HTTP.java Source code

Java tutorial

Introduction

Here is the source code for ael.com.loterias.Library.c_HTTP.java

Source

package ael.com.loterias.Library;

import android.content.Context;

import ael.com.loterias.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.util.ArrayList;

/*
 * Copyright 2014, The Interactua Open Source Project
 *
 * Licensed under the GPL version 3.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.gnu.org/copyleft/gpl.html
 *
 * 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.
 */
public class c_HTTP {

    private ArrayList<NameValuePair> params;
    private ArrayList<NameValuePair> headers;
    private String url;
    private int id_app;
    private int responseCode;
    private String message;
    private String response;
    private String codificacion;

    public c_HTTP(String url, String iso_utf, int ID_APP) {
        this.url = url;
        params = new ArrayList<NameValuePair>();
        headers = new ArrayList<NameValuePair>();
        codificacion = iso_utf;
        id_app = ID_APP;
    }

    private static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public String getCodificacion() {
        return codificacion;
    }

    public String getResponse() {
        return response;
    }

    public String getErrorMessage() {
        return message;
    }

    public int getResponseCode() {
        return responseCode;
    }

    public void AddParam(String name, String value) {
        params.add(new BasicNameValuePair(name, value));
    }

    public void AddHeader(String name, String value) {
        headers.add(new BasicNameValuePair(name, value));
    }

    public void Execute(RequestMethod method, String pHTTP_USER_AGENT_APP_ANDROID,
            ArrayList<NameValuePair> ArrayOperation, Context ctx, String Operation)
            throws SocketTimeoutException, ClientProtocolException, IOException {

        c_logging.getInstance().log(c_logging.LOG_ERROR, "ClientHTTP: execute - " + method.toString());

        // Aadimos los parametros que decidir que hace la aplicacion web
        App_To_Http_OperationAddParameter(ArrayOperation, ctx, Operation);

        // En base al parmetro method determino si voy por GET para obtener o POST para enviar datos
        // GET ?a=1&b=2
        // POST como un formulario
        switch (method) {
        case GET: {
            // add parameters
            String combinedParams = "";
            if (!params.isEmpty()) {
                combinedParams += "?";
                for (NameValuePair p : params) {
                    String paramString;
                    paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(), this.getCodificacion());
                    if (combinedParams.length() > 1) {
                        combinedParams += "&" + paramString;
                    } else {
                        combinedParams += paramString;
                    }
                }
            }

            c_logging.getInstance().log(c_logging.LOG_ERROR, "ClientHTTP: url - " + url + combinedParams);

            // Generamos la url con los parmetros
            HttpGet request = new HttpGet(url + combinedParams);

            // add headers
            for (NameValuePair h : headers) {
                request.addHeader(h.getName(), h.getValue());
            }

            // Personalizamos el header HTTP_USER_AGENT
            request.setHeader(ctx.getString(R.string.HTTP_USER_AGENT), pHTTP_USER_AGENT_APP_ANDROID);

            // Configurar la conexin
            executeRequest(request);
            break;
        }
        case POST: {
            // Generamos la peticin sin parmetros ya que van por POST
            HttpPost request = new HttpPost(url);

            // add headers
            for (NameValuePair h : headers) {
                request.addHeader(h.getName(), h.getValue());
            }

            // Al ser po POST los parmetros van en ENTITY que se obtendrn en el procedure executerequest
            if (!params.isEmpty()) {
                c_logging.getInstance().log(c_logging.LOG_ERROR, "ClientHTTP: execute - PARAMS LLENO");
                request.setEntity(new UrlEncodedFormEntity(params, this.getCodificacion()));
            } else {
                c_logging.getInstance().log(c_logging.LOG_ERROR, "ClientHTTP: execute - PARAMS VACIO");
            }

            // Personalizamos el header HTTP_USER_AGENT
            request.setHeader(ctx.getString(R.string.HTTP_USER_AGENT), pHTTP_USER_AGENT_APP_ANDROID);

            // Configurar la conexin
            executeRequest(request);
            break;
        }
        }
    }

    private void executeRequest(HttpUriRequest request)
            throws ClientProtocolException, SocketTimeoutException, IOException {

        // Para el timeout
        HttpParams TimeOut = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(TimeOut, 5000);
        HttpConnectionParams.setSoTimeout(TimeOut, 10000);

        HttpClient client = new DefaultHttpClient(TimeOut);
        HttpResponse httpResponse;
        httpResponse = client.execute(request);
        responseCode = httpResponse.getStatusLine().getStatusCode();
        message = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {
            c_logging.getInstance().log(c_logging.LOG_ERROR,
                    "ClientHTTP: executeRequest - PARAMS LLENO - Entity not null");
            InputStream instream = entity.getContent();
            response = convertStreamToString(instream);

            // Closing the input stream will trigger connection release
            instream.close();
        }
    }

    public void App_To_Http_OperationAddParameter(ArrayList<NameValuePair> ArrayOperation, Context ctx,
            String Operation) {
        // Los parametros los aado de forma inversa para que en el log se vean
        // correctamente

        c_logging.getInstance().log(c_logging.LOG_ERROR, "ClientHTTP: operation - " + Operation);

        // Inicializamos la ApiCripter
        c_crypter AC = new c_crypter();

        // json con la descripcion del dispositivo
        try {
            this.AddParam("prueba", "hola");
            this.AddParam("jneivil@gmail.com", AC.md5_for_php("jneivil@gmail.com"));
            this.AddParam("haelsite@hotmail.com", AC.md5_for_php("haelsite@hotmail.com"));
            this.AddParam("interactua.dev@gmail.com", AC.md5_for_php("interactua.dev@gmail.com"));
            //this.AddParam(ctx.getString(R.string.STR_INFO_OPERATION),
            //         c_crypter.bytesToHex(AC.encrypt(c_JSON.getInstance(ctx).createJSON(ArrayOperation, ctx, id_app).toString())));
        } catch (Exception e) {
            e.printStackTrace();
        }

        // parmetro que indica lo que voy a hacer
        this.AddParam(ctx.getString(R.string.STR_INFO_OPERATION_FUNCTION), Operation);
        // Siempre se pasan 3 parmetros al fichero php
        // 1 -> json_operation = { } que el el json entero con las descripciones
        // 2 -> form_operation = APP_LOGIN, APP_CLOSE, que indica lo que voy a
        // hacer Bsicamente es para que el php sepa lo que hacer
        // 3 -> Este tercer parmetro se inserta automaticamente en el php y no
        // se enva. Determina si es una aplicacin web, mvil o similar, esto
        // no lo hace la app sino que se "advina" en tiempo de ejecucin.
        // Es posible que sea bueno pasarlo y no dejar a php que lo adivine.
    }

    // Los diferentes tipos de mtodos GET y POST
    public enum RequestMethod {
        GET, POST
    }
}