本文主要是介绍http方式调用接口,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
话不多说,直接上代码
public class HttpRequestUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);
private static final String CHARSET_UTF_8 = "UTF-8";
private static final String HTTP = "http";
private static final String HTTPS = "https";
private static SSLConnectionSocketFactory sslsf = null;
private static PoolingHttpClientConnectionManager cm = null;
private static SSLContextBuilder builder = null;
static {
try {
builder = new SSLContextBuilder();
// 全部信任 不做身份鉴定
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
});
sslsf = new SSLConnectionSocketFactory(builder.build(),
new String[] { "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2" }, null, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
.register(HTTP, new PlainConnectionSocketFactory()).register(HTTPS, sslsf).build();
cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(1000);// max connection
} catch (Exception e) {
logger.error("ssl init error", e);
}
}
private HttpRequestUtils() {
}
public static String postWithStringParam(String url, Object toJson) {
return postWithStringParam(url, JsonUtils.objectToJson(toJson));
}
public static String postWithStringParam(String url, String stringParam) {
logger.info("url:{}, param:{}", url, stringParam);
CloseableHttpClient httpClient = null;
try {
int connectionTimeout = Integer.parseInt(getProperty("tbp.resource.web.connectionTimeout", "60000")) ;
int timeout = Integer.parseInt(getProperty("tbp.resource.web.timeout", "60000"));
int socketTimeout = Integer.parseInt(getProperty("tbp.resource.web.socketTimeout", "60000"));
httpClient = HttpClients.custom().disableAutomaticRetries().build();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeout)
.setConnectionRequestTimeout(timeout).setSocketTimeout(socketTimeout).build();
if(!StringUtils.isEmpty(stringParam)){
StringEntity entity = new StringEntity(stringParam, CHARSET_UTF_8);// 解决中文乱码问题
entity.setContentEncoding(CHARSET_UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
httpPost.setConfig(requestConfig);
return httpClient.execute(httpPost, new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws IOException {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
return EntityUtils.toString(response.getEntity(), CHARSET_UTF_8);
}
throw new IOException(response.toString());
}
});
} catch (IOException e) {
logger.error("HttpRequestUtils.postWithStringParam error,url:" + url + ",stringParam:" + stringParam, e);
throw new ResourceRuntimeException("网络繁忙,请稍后再试.");
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
}
/**
*
* 描述:(取资源文件里面的信息). <br/>
*
* @author 80000449 2018年11月6日下午8:28:00
*
* @param key
* @param defualtValue
* @return
*/
private static String getProperty(String key, String defualtValue){
return PropertiesManager.instance().getString(key, defualtValue);
}
/**
* 发送 SSL GET 请求(HTTPS)
*
* @param url
* @return
*/
public static String getSSL(String url) {
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm)
.setConnectionManagerShared(true).disableAutomaticRetries().build();
HttpGet httpGet = new HttpGet(url);
return httpClient.execute(httpGet, new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws IOException {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
return EntityUtils.toString(response.getEntity(), CHARSET_UTF_8);
}
return null;
}
});
} catch (IOException e) {
logger.error("HttpRequestUtils.getSSL error,url:" + url, e);
throw new ResourceRuntimeException(e);
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
}
/**
* 发送 SSL POST 请求(HTTPS)
*
* @param url
* @param toJson
* @return
*/
public static String postSSLWithJsonParam(String url, Object toJson) {
return postSSL(url, JsonUtils.objectToJson(toJson));
}
/**
* 发送 SSL POST 请求(HTTPS)
*
* @param url
* @param stringParam
* @return
*/
public static String postSSL(String url,String stringParam) {
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm)
.setConnectionManagerShared(true).disableAutomaticRetries().build();
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(stringParam, CHARSET_UTF_8);// 解决中文乱码问题
entity.setContentEncoding(CHARSET_UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
return httpClient.execute(httpPost, new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws IOException {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
return EntityUtils.toString(response.getEntity(), CHARSET_UTF_8);
}
return null;
}
});
} catch (IOException e) {
logger.error("HttpRequestUtils.postSSL error,url:" + url, e);
throw new ResourceRuntimeException(e);
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
}
}
使用方式
String result = HttpRequestUtils.postWithStringParam(taskUrl+"/fullDayResultService/fullDayActualDistance", params);// params 不传可为null
这篇关于http方式调用接口的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!