import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {
public static String post(String url, List params, int retrys) {
CloseableHttpResponse response = null;
CloseableHttpClient httpclient = null;
try {
httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(6000).setConnectTimeout(3000).build();
httppost.setConfig(requestConfig);
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
System.out.println("executing request " + httppost.getURI());
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity);
} else {
return "";
}
} catch (Exception e) {
if (retrys > 0) {
return post(url, params, retrys - 1);
} else {
//TODO: add log
return "";
}
} finally {
HttpClientUtils.closeQuietly(response);
HttpClientUtils.closeQuietly(httpclient);
}
}
public static String get(String url, List params, int retrys) {
CloseableHttpResponse response = null;
CloseableHttpClient httpclient = null;
try {
httpclient = HttpClients.createDefault();
URIBuilder builder = new URIBuilder(url);
if (null != params && !params.isEmpty()) {
builder.addParameters(params);
}
HttpGet httpget = new HttpGet(builder.toString());
System.out.println("executing request " + httpget.getURI());
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(6000).setConnectTimeout(3000).build();
httpget.setConfig(requestConfig);
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity);
} else {
return "";
}
} catch (Exception e) {
if (retrys > 0) {
return get(url, params, retrys - 1);
} else {
//TODO:add log
return "";
}
} finally {
HttpClientUtils.closeQuietly(response);
HttpClientUtils.closeQuietly(httpclient);
}
}
public static void main(String[] args) {
String url = "http://xxxxx/trace/v2/entity/list";
List params = new ArrayList<>();
params.add(new BasicNameValuePair("ak", "xxxxxxxx"));
params.add(new BasicNameValuePair("service_id", "xxxxxx"));
System.out.println(get(url, params, 3));
url = "http://xxxxx/trace/v2/entity/add";
params.add(new BasicNameValuePair("entity_name", "xx"));
System.out.println(post(url, params, 3));
}
}
httpclient版本:4.5.1