HttpSender.java 16.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
package com.focasoftware.deboinventario;

import android.os.Environment;
import android.os.SystemClock;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Objects;

import static org.apache.http.HttpHeaders.IF;

/**
 * Clase para manejar conexiones Http con un webservice o servidor web,
 * utilizada para enviar informaci�n a los webServices
 *
 * @author GuillermoR
 *
 */
public class HttpSender {

	/**
	 * Variable de codigo de soft o funcion del webservice
	 */
	private String cod_soft;
	/**
	 * URL de destino desde donde consumir el webservice
	 */
	private String url_destinacion;

	String sdcard = Environment.getExternalStorageDirectory().toString();

	/**
	 * Constructr que provee el codigo de software a ejeuctar en el URL destino
	 * <p>
	 * 1� Setea el codigo de software
	 * <p>
	 * 2� Setea la URL de destino
	 * <p>
	 * 3� Se valida la url
	 *
	 * @param codigo_software
	 * @throws ExceptionHttpExchange
	 */
	public HttpSender(String codigo_software) throws ExceptionHttpExchange {

		// 1� Setea el codigo de software
		cod_soft = codigo_software;
		// 2� Setea la URL de destino
		url_destinacion = Parametros.PREF_URL_CONEXION_SERVIDOR;
		// 3� Se valida la url
		URLValidator.esValidaEstaURL(url_destinacion);

	}

	/**
	 * Funci�n para enviar un archivo a procesarse con el numeroo de funcion
	 * correspondiente
	 * <p>
	 * 1� Creamos el archivo
	 * <p>
	 * 2� Creamos un cliente Http
	 * <p>
	 * 3� Configuramos el URL de destino para usar el metodo post
	 * <p>
	 * 4� Generamos el FileBody y la entidad multiparte de request
	 * <p>
	 * 5� Pasamos los parametros al request
	 * <p>
	 * 6� Ejecutamos la llamada a ese request
	 * <p>
	 * 7� Obtenemos el XML en formato String
	 * <p>
	 * 8� Verificamos la correcta ejecuci�n
	 *
	 * @param url_archivo_que_mandar
	 * @param numero_funcion
	 * @return
	 */
	public boolean send_xml(String url_archivo_que_mandar, String numero_funcion) {
		System.out.println("::: HTTPSEnder sector 1");
		try {
			// 1� Creamos el archivo
			File file = new File(url_archivo_que_mandar);
			// 2� Creamos un cliente Http
			HttpClient client = new DefaultHttpClient();
			// 3� Configuramos el URL de destino para usar el metodo post
			String postURL = url_destinacion;
			HttpPost post = new HttpPost(postURL);
			// 4� Generamos el FileBody y la entidad multiparte de request
			FileBody bin = new FileBody(file, "text/xml");
			System.out.println("::: HTTPSEnder sector :"+bin);
			MultipartEntity reqEntity = new MultipartEntity();

			// 5� Pasamos los parametros al request
			reqEntity.addPart(Parametros.codigo_soft, new StringBody(cod_soft));
			reqEntity.addPart(Parametros.codigo_fonc, new StringBody(numero_funcion));
			reqEntity.addPart(Parametros.codigo_tab, new StringBody(Parametros.PREF_NUMERO_DE_TERMINAL));
			reqEntity.addPart(Parametros.codigo_post, bin);
			post.setEntity(reqEntity);

			/*
			 * NB: List<NameValuePair> nameValuePairs = new
			 * ArrayList<NameValuePair>(2); nameValuePairs.add(new
			 * BasicNameValuePair("a", "1")); nameValuePairs.add(new
			 * BasicNameValuePair("b", "4")); try { post.setEntity(new
			 * UrlEncodedFormEntity(nameValuePairs)); } catch
			 * (UnsupportedEncodingException unEnEx) { unEnEx.printStackTrace();
			 * }
			 */

			// 6� Ejecutamos la llamada a ese request
			HttpResponse response = client.execute(post);
			HttpEntity resEntity = response.getEntity();
			// 7� Obtenemos el XML en formato String
			String xmlString = EntityUtils.toString(resEntity);

			Log.v("yo", "El resultado del http sender es :" + xmlString);

			// 8� Verificamos la correcta ejecuci�n
			if (!xmlString.contains("EXITO")) {
				return false;
			}

			return true;

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * Funcion que manda un archivo xml pasado por parametro a una url
	 * almacenada en la variable de clase
	 *
	 * @param url_archivo_que_mandar
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public boolean send_xml(String url_archivo_que_mandar) {

		try {

			File file = new File(url_archivo_que_mandar);

			HttpClient client = new DefaultHttpClient();
			String postURL = url_destinacion;

			HttpPost post = new HttpPost(postURL);
			System.out.println("::: HTTPSEnder sector 2");
			FileBody bin = new FileBody(file);

			MultipartEntity reqEntity = new MultipartEntity();
			reqEntity.addPart(Parametros.codigo_soft, new StringBody(cod_soft));
			reqEntity.addPart(Parametros.codigo_fonc, new StringBody(Parametros.CODIGO_FONC_EXPORT_DATOS));
// && !Objects.equals(Parametros.PREF_NUMERO_DE_TERMINAL,0)
			if(Parametros.PREF_NUMERO_DE_TERMINAL!=null){
				reqEntity.addPart(Parametros.codigo_tab, new StringBody(Parametros.PREF_NUMERO_DE_TERMINAL));
			}else{
				reqEntity.addPart(Parametros.codigo_tab, new StringBody("1"));
			}

			reqEntity.addPart(Parametros.codigo_post, bin);
			post.setEntity(reqEntity);
			HttpResponse response = client.execute(post);
			HttpEntity resEntity = response.getEntity();
			String xmlString = EntityUtils.toString(resEntity);

			System.out.println("::: HttpSender 184 xmlstring " + xmlString);

			return xmlString.contains("EXITO");

		} catch (Exception e) {
			System.out.println("::: HTTPSEnder catch");
			e.printStackTrace();

			return false;
		}

	}

	/**
	 * Funcion que manda un archivo xml pasado por parametro a una url
	 * almacenada en la variable de clase
	 *
	 * @param url_archivo_que_mandar
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public boolean send_compra_xml(String url_archivo_que_mandar) {

		try {

			File file = new File(url_archivo_que_mandar);

			HttpClient client = new DefaultHttpClient();
			String postURL = url_destinacion;

			HttpPost post = new HttpPost(postURL);
			System.out.println("::: HTTPSEnder Compras export 217");
			FileBody bin = new FileBody(file);

			MultipartEntity reqEntity = new MultipartEntity();
			reqEntity.addPart(Parametros.codigo_soft, new StringBody(cod_soft));
			reqEntity.addPart(Parametros.codigo_fonc, new StringBody(Parametros.CODIGO_FONC_EXPORT_COMPRAS));
			reqEntity.addPart(Parametros.codigo_tab, new StringBody(Parametros.PREF_NUMERO_DE_TERMINAL));
			reqEntity.addPart(Parametros.codigo_post, bin);
			post.setEntity(reqEntity);
			HttpResponse response = client.execute(post);
			HttpEntity resEntity = response.getEntity();
			String xmlString = EntityUtils.toString(resEntity);

			System.out.println("::: HttpSender 232 Compras xmlstring " + xmlString);

			return xmlString.contains("EXITO");

		} catch (Exception e) {
			System.out.println("::: HTTPSEnder catch");
			e.printStackTrace();

			return false;
		}

	}

	/**
	 * Funcion que envia un archivo txt pasado como parametro a una url
	 * almacenada
	 *
	 * @param url_archivo_que_mandar
	 * @return
	 */
	public boolean send_txt(String url_archivo_que_mandar) {
		System.out.println("::: HTTPSEnder sector 3");
		try {

			File file = new File(url_archivo_que_mandar);

			HttpClient client = new DefaultHttpClient();
			String postURL = url_destinacion;
			HttpPost post = new HttpPost(postURL);
			FileBody bin = new FileBody(file, "text/plain");
			MultipartEntity reqEntity = new MultipartEntity();

			reqEntity.addPart(Parametros.codigo_soft, new StringBody(cod_soft));
			reqEntity.addPart(Parametros.codigo_fonc, new StringBody(Parametros.CODIGO_FONC_EXPORT_LOGS));
			reqEntity.addPart(Parametros.codigo_tab, new StringBody(Parametros.PREF_NUMERO_DE_TERMINAL));
			reqEntity.addPart(Parametros.codigo_text, bin);
			post.setEntity(reqEntity);

			/*
			 * NB: List<NameValuePair> nameValuePairs = new
			 * ArrayList<NameValuePair>(2); nameValuePairs.add(new
			 * BasicNameValuePair("a", "1")); nameValuePairs.add(new
			 * BasicNameValuePair("b", "4")); try { post.setEntity(new
			 * UrlEncodedFormEntity(nameValuePairs)); } catch
			 * (UnsupportedEncodingException unEnEx) { unEnEx.printStackTrace();
			 * }
			 */

			HttpResponse response = client.execute(post);
			HttpEntity resEntity = response.getEntity();
			String xmlString = EntityUtils.toString(resEntity);

			if (!xmlString.contains("EXITO")) {
				return false;

			}
			return true;

		} catch (Exception e) {

			e.printStackTrace();
			return false;
		}
	}

	/**
	 * Funcion para enviar una foto a la URL almacenada en la variable de clase
	 * correspondiente
	 *
	 * @param url_foto_que_mandar
	 * @return
	 */
	public boolean send_foto(String url_foto_que_mandar) {

		try {
			File file = new File(url_foto_que_mandar);
			HttpClient client = new DefaultHttpClient();
			String postURL = url_destinacion;
			HttpPost post = new HttpPost(postURL);
			FileBody bin = new FileBody(file, "image/jpeg");
			MultipartEntity reqEntity = new MultipartEntity();

			reqEntity.addPart(Parametros.codigo_soft, new StringBody(cod_soft));
			reqEntity.addPart(Parametros.codigo_fonc, new StringBody(Parametros.CODIGO_FONC_EXPORT_FOTOS));
			reqEntity.addPart(Parametros.codigo_tab, new StringBody(Parametros.PREF_NUMERO_DE_TERMINAL));
			reqEntity.addPart(Parametros.codigo_foto, bin);

			post.setEntity(reqEntity);

			/*
			 * NB: NO ES POSIBLE AGREGAR EN POST DIFERENTES TIPOS, TIENEN QUE
			 * SER DEL TIPO "ADDPART" List<NameValuePair> nameValuePairs = new
			 * ArrayList<NameValuePair>(2); nameValuePairs.add(new
			 * BasicNameValuePair("a", "1")); nameValuePairs.add(new
			 * BasicNameValuePair("b", "4")); try { post.setEntity(new
			 * UrlEncodedFormEntity(nameValuePairs)); } catch
			 * (UnsupportedEncodingException unEnEx) { unEnEx.printStackTrace();
			 * }
			 */

			HttpResponse response = client.execute(post);
			HttpEntity resEntity = response.getEntity();

			if (resEntity != null) {
				String xmlString = EntityUtils.toString(resEntity);

				if (!xmlString.contains("EXITO")) {
					return false;
				}
			}

			SystemClock.sleep(500);
			return true;

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * Envia informaci�n del estado de liberacion de cierto invenatrio pasado
	 * como parametro
	 *
	 * @param numero_inventario
	 * @param estado_liberatorio
	 * @return
	 */
	public boolean send_liberacion(int numero_inventario, int estado_liberatorio) {
		try {
			HttpClient client = new DefaultHttpClient();
			String postURL = url_destinacion;
			HttpPost post = new HttpPost(postURL);
			MultipartEntity reqEntity = new MultipartEntity();

			reqEntity.addPart(Parametros.codigo_soft, new StringBody(cod_soft));
			reqEntity.addPart(Parametros.codigo_fonc, new StringBody(Parametros.CODIGO_FONC_EXPORT_LIBERACION));

			String strFinal = String.valueOf(numero_inventario) + ","
					+ String.valueOf(estado_liberatorio);
			reqEntity.addPart(Parametros.codigo_opc, new StringBody(strFinal));

			post.setEntity(reqEntity);

			/*
			 * NB: NO ES POSIBLE AGREGAR EN POST DIFERENTES TIPOS, TIENEN QUE
			 * SER DEL TIPO "ADDPART" List<NameValuePair> nameValuePairs = new
			 * ArrayList<NameValuePair>(2); nameValuePairs.add(new
			 * BasicNameValuePair("a", "1")); nameValuePairs.add(new
			 * BasicNameValuePair("b", "4")); try { post.setEntity(new
			 * UrlEncodedFormEntity(nameValuePairs)); } catch
			 * (UnsupportedEncodingException unEnEx) { unEnEx.printStackTrace();
			 * }
			 */

			HttpResponse response = client.execute(post);
			HttpEntity resEntity = response.getEntity();
			String xmlString = "";

			if (resEntity != null) {
				xmlString = EntityUtils.toString(resEntity);
			}

			if (!xmlString.contains("EXITO")) {
				return false;
			}

			SystemClock.sleep(500);
			return true;

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * Envia informacion de estado de liberacion de varios inventario pasados en
	 * forma de lista de enteros
	 *
	 * @param listaIds
	 * @return
	 */
	public boolean send_liberacion(ArrayList<Integer> listaIds) {
		try {
			HttpClient client = new DefaultHttpClient();
			String postURL = url_destinacion;
			HttpPost post = new HttpPost(postURL);
			MultipartEntity reqEntity = new MultipartEntity();

			reqEntity.addPart(Parametros.codigo_soft, new StringBody(cod_soft));
			reqEntity.addPart(Parametros.codigo_fonc, new StringBody(
					Parametros.CODIGO_FONC_EXPORT_LIBERACION));

			String strFinal = "";
			for (int param : listaIds) {
				strFinal = strFinal + String.valueOf(param) + ",";
			}
			// Sacamos el �ltimo "," de la cadena de caracteres:
			strFinal = strFinal.substring(0, strFinal.length() - 1);
			reqEntity.addPart(Parametros.codigo_opc, new StringBody(strFinal));

			post.setEntity(reqEntity);

			/*
			 * NB: NO ES POSIBLE AGREGAR EN POST DIFERENTES TIPOS, TIENEN QUE
			 * SER DEL TIPO "ADDPART" List<NameValuePair> nameValuePairs = new
			 * ArrayList<NameValuePair>(2); nameValuePairs.add(new
			 * BasicNameValuePair("a", "1")); nameValuePairs.add(new
			 * BasicNameValuePair("b", "4")); try { post.setEntity(new
			 * UrlEncodedFormEntity(nameValuePairs)); } catch
			 * (UnsupportedEncodingException unEnEx) { unEnEx.printStackTrace();
			 * }
			 */

			HttpResponse response = client.execute(post);
			HttpEntity resEntity = response.getEntity();
			String xmlString = "";

			if (resEntity != null) {
				xmlString = EntityUtils.toString(resEntity);
			}

			if (xmlString.contains("EXITO") == false) {
				return false;
			}

			SystemClock.sleep(500);
			return true;

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * Funcion generica de envio de archivos? o manda fotos tambien?
	 *
	 * @param url_file
	 * @return
	 */
	public boolean send_file(String url_file) {

		try {
			File file = new File(url_file);
			HttpClient client = new DefaultHttpClient();
			String postURL = url_destinacion;
			HttpPost post = new HttpPost(postURL);
			FileBody bin = new FileBody(file, "text/xml");
			MultipartEntity reqEntity = new MultipartEntity();

			reqEntity.addPart(Parametros.codigo_soft, new StringBody(cod_soft));
			reqEntity.addPart(Parametros.codigo_fonc, new StringBody(
					Parametros.CODIGO_FONC_EXPORT_FOTOS));
			reqEntity.addPart(Parametros.codigo_tab, new StringBody(
					Parametros.PREF_NUMERO_DE_TERMINAL));
			reqEntity.addPart(Parametros.codigo_xfile, bin);

			post.setEntity(reqEntity);

			/*
			 * NB: NO ES POSIBLE AGREGAR EN POST DIFERENTES TIPOS, TIENEN QUE
			 * SER DEL TIPO "ADDPART" List<NameValuePair> nameValuePairs = new
			 * ArrayList<NameValuePair>(2); nameValuePairs.add(new
			 * BasicNameValuePair("a", "1")); nameValuePairs.add(new
			 * BasicNameValuePair("b", "4")); try { post.setEntity(new
			 * UrlEncodedFormEntity(nameValuePairs)); } catch
			 * (UnsupportedEncodingException unEnEx) { unEnEx.printStackTrace();
			 * }
			 */

			HttpResponse response = client.execute(post);
			HttpEntity resEntity = response.getEntity();

			if (resEntity != null) {
				String xmlString = EntityUtils.toString(resEntity);

				if (xmlString.contains("EXITO") == false) {
					return false;
				}
			}

			SystemClock.sleep(500);
			return true;

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public void copyFile(File sourceFile, File destFile) throws IOException {
		try {
			if (!sourceFile.exists()) {
				return;
			}
			if (!destFile.exists()) {
				destFile.createNewFile();
			}
			FileChannel source = null;
			FileChannel destination = null;
			source = new FileInputStream(sourceFile).getChannel();
			destination = new FileOutputStream(destFile).getChannel();
			if (destination != null && source != null) {
				destination.transferFrom(source, 0, source.size());
			}
			if (source != null) {
				source.close();
			}
			if (destination != null) {
				destination.close();
			}
		} catch (Exception e) {
		}
	}

}