use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project swift by luastar.
the class HttpClientUtils method get.
public static String get(HttpParam param) {
CloseableHttpClient httpclient = null;
CloseableHttpResponse response = null;
try {
HttpGet httpGet = new HttpGet(param.getUrl());
// 超时设置
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(param.getTimeout()).setConnectTimeout(param.getTimeout()).setConnectionRequestTimeout(param.getTimeout()).build();
httpGet.setConfig(requestConfig);
// head设置
if (ObjUtils.isNotEmpty(param.getHeaderMap())) {
for (Map.Entry<String, String> entry : param.getHeaderMap().entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
}
// requestId
String requestId = ObjUtils.ifEmpty(MDC.get(MDC_KEY_REQUESTID), MDC.get(MDC_KEY_REQUEST_ID));
if (ObjUtils.isNotEmpty(requestId)) {
httpGet.setHeader(MDC_KEY_REQUESTID, requestId);
}
httpclient = createHttpClient(param.getUrl());
long start = System.currentTimeMillis();
response = httpclient.execute(httpGet);
long end = System.currentTimeMillis();
int status = response.getStatusLine().getStatusCode();
logger.info("请求url:{},结果状态:{},耗时:{}毫秒。", param.getUrl(), status, ((end - start)));
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity, param.getCharset()) : null;
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
org.apache.http.client.utils.HttpClientUtils.closeQuietly(response);
org.apache.http.client.utils.HttpClientUtils.closeQuietly(httpclient);
}
return null;
}
use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project swift by luastar.
the class HttpClientUtils method postHttpResult.
public static HttpResult postHttpResult(HttpParam param) {
CloseableHttpClient httpclient = null;
CloseableHttpResponse response = null;
HttpResult result = new HttpResult();
try {
HttpPost httpPost = new HttpPost(param.getUrl());
// 超时设置
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(param.getTimeout()).setConnectTimeout(param.getTimeout()).setConnectionRequestTimeout(param.getTimeout()).build();
httpPost.setConfig(requestConfig);
// head设置
if (ObjUtils.isNotEmpty(param.getHeaderMap())) {
for (Map.Entry<String, String> entry : param.getHeaderMap().entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
// requestId
String requestId = ObjUtils.ifEmpty(MDC.get(MDC_KEY_REQUESTID), MDC.get(MDC_KEY_REQUEST_ID));
if (ObjUtils.isNotEmpty(requestId)) {
httpPost.setHeader(MDC_KEY_REQUESTID, requestId);
}
// 参数设置
if (ObjUtils.isNotEmpty(param.getParamMap())) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, String> entry : param.getParamMap().entrySet()) {
// 如果没有按泛型传,需要将值转换为字符串
nvps.add(new BasicNameValuePair(entry.getKey(), ObjUtils.toString(entry.getValue())));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, param.getCharset()));
}
httpclient = createHttpClient(param.getUrl());
long start = System.currentTimeMillis();
response = httpclient.execute(httpPost);
long end = System.currentTimeMillis();
int status = response.getStatusLine().getStatusCode();
logger.info("请求url:{},结果状态:{},耗时:{}毫秒。", param.getUrl(), status, (end - start));
result.setStatus(status);
result.setCost(end - start);
result.setHeaders(response.getAllHeaders());
HttpEntity entity = response.getEntity();
if (entity != null) {
byte[] content = EntityUtils.toByteArray(entity);
if (content != null) {
result.setInputStream(new ByteArrayInputStream(content));
}
}
return result;
} catch (Exception e) {
logger.error(e.getMessage(), e);
result.setStatus(HttpResult.STATUS_EXP);
result.setException(e);
} finally {
org.apache.http.client.utils.HttpClientUtils.closeQuietly(response);
org.apache.http.client.utils.HttpClientUtils.closeQuietly(httpclient);
}
return result;
}
use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project keycloak by keycloak.
the class OAuthRedirectUriTest method testWithCustomScheme.
@Test
public void testWithCustomScheme() throws IOException {
oauth.clientId("custom-scheme");
oauth.redirectUri("android-app://org.keycloak.examples.cordova/https/keycloak-cordova-example.github.io/login");
oauth.openLoginForm();
RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
CookieStore cookieStore = new BasicCookieStore();
HttpClientContext context = HttpClientContext.create();
context.setCookieStore(cookieStore);
String loginUrl = driver.getCurrentUrl();
CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();
try {
String loginPage = SimpleHttp.doGet(loginUrl, client).asString();
String formAction = loginPage.split("action=\"")[1].split("\"")[0].replaceAll("&", "&");
SimpleHttp.Response response = SimpleHttp.doPost(formAction, client).param("username", "test-user@localhost").param("password", "password").asResponse();
response.getStatus();
assertThat(response.getFirstHeader("Location"), Matchers.startsWith("android-app://org.keycloak.examples.cordova/https/keycloak-cordova-example.github.io/login"));
} finally {
client.close();
}
}
use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project keycloak by keycloak.
the class HttpClientBuilder method build.
public CloseableHttpClient build() {
X509HostnameVerifier verifier = null;
if (this.verifier != null)
verifier = new VerifierWrapper(this.verifier);
else {
switch(policy) {
case ANY:
verifier = new AllowAllHostnameVerifier();
break;
case WILDCARD:
verifier = new BrowserCompatHostnameVerifier();
break;
case STRICT:
verifier = new StrictHostnameVerifier();
break;
}
}
try {
SSLConnectionSocketFactory sslsf = null;
SSLContext theContext = sslContext;
if (disableTrustManager) {
theContext = SSLContext.getInstance("TLS");
theContext.init(null, new TrustManager[] { new PassthroughTrustManager() }, new SecureRandom());
verifier = new AllowAllHostnameVerifier();
sslsf = new SSLConnectionSocketFactory(theContext, verifier);
} else if (theContext != null) {
sslsf = new SSLConnectionSocketFactory(theContext, verifier);
} else if (clientKeyStore != null || truststore != null) {
theContext = createSslContext("TLS", clientKeyStore, clientPrivateKeyPassword, truststore, null);
sslsf = new SSLConnectionSocketFactory(theContext, verifier);
} else {
final SSLContext tlsContext = SSLContext.getInstance("TLS");
tlsContext.init(null, null, null);
sslsf = new SSLConnectionSocketFactory(tlsContext, verifier);
}
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout((int) establishConnectionTimeout).setSocketTimeout((int) socketTimeout).setExpectContinueEnabled(expectContinueEnabled).build();
org.apache.http.impl.client.HttpClientBuilder builder = HttpClients.custom().setDefaultRequestConfig(requestConfig).setSSLSocketFactory(sslsf).setMaxConnTotal(connectionPoolSize).setMaxConnPerRoute(maxPooledPerRoute).setConnectionTimeToLive(connectionTTL, connectionTTLUnit);
if (!reuseConnections) {
builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
}
if (proxyMappings != null && !proxyMappings.isEmpty()) {
builder.setRoutePlanner(new ProxyMappingsAwareRoutePlanner(proxyMappings));
}
if (maxConnectionIdleTime > 0) {
// Will start background cleaner thread
builder.evictIdleConnections(maxConnectionIdleTime, maxConnectionIdleTimeUnit);
}
if (disableCookies)
builder.disableCookieManagement();
if (!reuseConnections) {
builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
}
return builder.build();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project SEPA by arces-wot.
the class SPARQL11Protocol method post.
/**
* <a href="https://www.w3.org/TR/sparql11-protocol/"> SPARQL 1.1 Protocol</a>
*
* *
*
* <pre>
* HTTP Method Query String Parameters Request Content Type Request Message Body
*----------------------------------------------------------------------------------------------------------------------------------------
* update via URL-encoded POST| POST None application/x-www-form-urlencoded URL-encoded, ampersand-separated query parameters.
* | update (exactly 1)
* | using-graph-uri (0 or more)
* | using-named-graph-uri (0 or more)
*----------------------------------------------------------------------------------------------------------------------------------------
* update via POST directly | POST using-graph-uri (0 or more) application/sparql-update Unencoded SPARQL update request string
* using-named-graph-uri (0 or more)
* </pre>
*/
private Response post(UpdateRequest req) {
StringEntity requestEntity = null;
HttpPost post;
String graphs = null;
// Setting URL
String scheme = req.getScheme();
String host = req.getHost();
int port = req.getPort();
String updatePath = req.getPath();
// Create POST request
try {
if (req.getHttpMethod().equals(UpdateHTTPMethod.POST)) {
// Graphs
for (String g : req.getDefaultGraphUri()) {
if (graphs == null)
graphs = "using-graph-uri=" + g;
else
graphs += "&using-graph-uri=" + g;
}
for (String g : req.getNamedGraphUri()) {
if (graphs == null)
graphs = "using-named-graph-uri=" + g;
else
graphs += "&using-named-graph-uri=" + g;
}
post = new HttpPost(new URI(scheme, null, host, port, updatePath, graphs, null));
post.setHeader("Content-Type", "application/sparql-update");
// Body
requestEntity = new StringEntity(req.getSPARQL(), Consts.UTF_8);
} else {
// Graphs
for (String g : req.getDefaultGraphUri()) {
if (graphs == null)
graphs = "using-graph-uri=" + URLEncoder.encode(g, "UTF-8");
else
graphs += "&using-graph-uri=" + URLEncoder.encode(g, "UTF-8");
}
for (String g : req.getNamedGraphUri()) {
if (graphs == null)
graphs = "using-named-graph-uri=" + URLEncoder.encode(g, "UTF-8");
else
graphs += "&using-named-graph-uri=" + URLEncoder.encode(g, "UTF-8");
}
post = new HttpPost(new URI(scheme, null, host, port, updatePath, null, null));
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
// Body
if (graphs != null)
requestEntity = new StringEntity("update=" + URLEncoder.encode(req.getSPARQL(), "UTF-8") + "&" + graphs, Consts.UTF_8);
else
requestEntity = new StringEntity("update=" + URLEncoder.encode(req.getSPARQL(), "UTF-8"), Consts.UTF_8);
}
} catch (URISyntaxException e) {
logger.error(e.getMessage());
return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "URISyntaxException", e.getMessage());
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage());
return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "UnsupportedEncodingException", e.getMessage());
}
// Accept header
post.setHeader("Accept", req.getAcceptHeader());
// Body
post.setEntity(requestEntity);
// Setting timeout
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout((int) req.getTimeout()).setConnectTimeout((int) req.getTimeout()).build();
post.setConfig(requestConfig);
// Add "Authorization" header if required
String authorizationHeader = req.getAuthorizationHeader();
if (authorizationHeader != null) {
post.setHeader("Authorization", authorizationHeader);
}
return executeRequest(post, req);
}
Aggregations