private static CloseableHttpClient getHttpClient() {
CloseableHttpClient httpclient = HttpClients.createDefault();
return httpclient;
}
public static JSONObject exeHttpServiceGET(String url) {
JSONObject o = null;
try {
HttpGet request = new HttpGet(url);
request.addHeader("accept", "application/json");
try (
CloseableHttpResponse response = getHttpClient().execute(request)) {
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
StringBuilder result = new StringBuilder();
while ((line = rd.readLine()) != null) {
// System.out.println(line);
result.append(line);
}
o = new JSONObject(toUTF8(result.toString()));
Header[] headers = response.getAllHeaders();
}
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
return o;
}
public static JSONObject exeHttpServicePOST(String url) {
JSONObject o = null;
try {
HttpPost request = new HttpPost(url);
request.addHeader("accept", "application/json");
try (
CloseableHttpResponse response = getHttpClient().execute(request)) {
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
StringBuilder result = new StringBuilder();
while ((line = rd.readLine()) != null) {
// System.out.println(line);
result.append(line);
}
o = new JSONObject(result.toString());
}
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
return o;
}
public static JSONObject exeHttpServicePOST(String url, JSONObject body) {
System.out.println("url: " + url);
System.out.println("body: " + body.toString());
JSONObject o = null;
try {
StringEntity input = new StringEntity(body.toString(), ContentType.APPLICATION_JSON);
HttpPost request = new HttpPost(url);
request.setEntity(input);
request.addHeader("Content-Type", "application/json");
request.addHeader("Accept", "application/json");
try (
CloseableHttpResponse response = getHttpClient().execute(request)) {
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
StringBuilder result = new StringBuilder();
System.out.println("imprimiendo respuesta...");
while ((line = rd.readLine()) != null) {
System.out.println(line);
result.append(line);
}
System.out.println("POST restult: " + result.length() + " " + result.toString());
o = result.length() == 0 ? new JSONObject() : new JSONObject(toUTF8(result.toString()));
}
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
return o;
}