edu.uvm.ccts.common.util.HttpUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of ccts-common Show documentation
Show all versions of ccts-common Show documentation
A library of useful generic objects and tools consolidated here to simplify all UVM CCTS projects
/*
* Copyright 2015 The University of Vermont and State
* Agricultural College. All rights reserved.
*
* Written by Matthew B. Storer
*
* This file is part of CCTS Common.
*
* CCTS Common is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CCTS Common is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CCTS Common. If not, see .
*/
package edu.uvm.ccts.common.util;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
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.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by mbstorer on 8/12/15.
*/
public class HttpUtil {
private static final Log log = LogFactory.getLog(HttpUtil.class);
private static final int DFLT_ATTEMPTS = 3;
private static final int DFLT_TIMEOUT_SECONDS = 60;
public static String get(String url) throws IOException, InterruptedException {
return get(url, DFLT_ATTEMPTS, DFLT_TIMEOUT_SECONDS);
}
public static String get(String url, int maxAttempts, int timeoutSeconds) throws IOException, InterruptedException {
HttpGet httpGet = new HttpGet(url);
setTimeout(httpGet, timeoutSeconds);
return executeRequest(httpGet, maxAttempts);
}
public static String post(String url, Map params) throws IOException, InterruptedException {
return post(url, params, DFLT_ATTEMPTS, DFLT_TIMEOUT_SECONDS);
}
public static String post(String url, Map params, int maxAttempts, int timeoutSeconds)
throws IOException, InterruptedException {
HttpPost httpPost = new HttpPost(url);
setTimeout(httpPost, timeoutSeconds);
if (params != null && params.size() > 0) {
List paramList = new ArrayList();
for (Map.Entry entry : params.entrySet()) {
String name = entry.getKey();
String value = String.valueOf(entry.getValue());
paramList.add(new BasicNameValuePair(name, value));
}
httpPost.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
}
return executeRequest(httpPost, maxAttempts);
}
//////////////////////////////////////////////////////////////////////////////////////////////
// private methods
//
private static void setTimeout(HttpRequestBase request, int timeoutSeconds) {
if (timeoutSeconds < 0) {
log.debug("setTimeout : invalid timeoutSeconds value (" + timeoutSeconds + ") - disabling timeout");
timeoutSeconds = 0;
}
if (timeoutSeconds > 0) {
int timeoutMS = timeoutSeconds * 1000;
RequestConfig config = RequestConfig.copy(RequestConfig.DEFAULT)
.setSocketTimeout(timeoutMS)
.setConnectTimeout(timeoutMS)
.setConnectionRequestTimeout(timeoutMS)
.build();
request.setConfig(config);
}
}
private static String executeRequest(HttpUriRequest request, int maxAttempts) throws IOException, InterruptedException {
HttpClient httpClient = HttpClients.createDefault();
if (maxAttempts < 1) {
log.debug("executeRequest : invalid maxAttempts value (" + maxAttempts + ") - setting to 1");
maxAttempts = 1;
}
int attempt = 1;
boolean success = false;
HttpEntity httpEntity = null;
while ( ! success && attempt <= maxAttempts ) {
try {
httpEntity = httpClient.execute(request).getEntity();
success = true;
} catch (IOException e) {
if (attempt == maxAttempts) {
throw e;
} else {
log.warn("executeRequest : caught " + e.getClass().getName() + " - " + e.getMessage());
log.info("executeRequest : will try again in 30 seconds (attempt " + attempt + " of " + maxAttempts + ")");
}
Thread.sleep(30 * 1000);
attempt ++;
}
}
if (httpEntity != null) {
InputStream in = null;
try {
in = new BufferedInputStream(httpEntity.getContent());
StringWriter writer = new StringWriter();
IOUtils.copy(in, writer, "UTF-8");
return writer.toString();
} finally {
if (in != null) in.close();
}
}
return null;
}
}