All Downloads are FREE. Search and download functionalities are using the official Maven repository.

br.com.behaviortest.api.integration.AbstractGetway Maven / Gradle / Ivy

There is a newer version: 1.0.1
Show newest version
package br.com.behaviortest.api.integration;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;

import br.com.behaviortest.model.dto.Response;
import br.com.behaviortest.util.StringUtil;

/**
 * @author 		Felipe Rudolfe
 * @since  		16 de jan de 2020
 */
public class AbstractGetway {

	protected AbstractGetway() {}

	@SuppressWarnings("unchecked")
	public static  R request(String urlRequest, String method, Object data, Class response, Map headers,
			Map params) throws IOException {

		R retorno = null;

		String param = "";
		if ( params != null) {
			for (Entry item : params.entrySet()) {
				if ("".endsWith(param)) {
					param += "?";
				} else {
					param += "&";
				}
				param += item.getKey() + "=" + item.getValue();
			}
		}

		URL url = new URL(urlRequest + param);

		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod(method);

		if ( headers != null) {
			for (Entry header : headers.entrySet()) {
				conn.setRequestProperty(header.getKey(), header.getValue());
			}
		}

		if (data != null) {

			String str =  StringUtil.toJson(data);
			byte[] outputInBytes = str.getBytes("UTF-8");

			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.getOutputStream().write(outputInBytes);
		}

		if (conn.getResponseCode() != 200) {
			throw new RuntimeException("HTTP error code : " + conn.getResponseCode() + " - " + conn.getResponseMessage());
		}

		BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

		String output;
		while ((output = br.readLine()) != null) {
			retorno = (R) StringUtil.fromJson(output, Response.class);
		}

		return retorno;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy