List of usage examples for org.apache.http.client.protocol HttpClientContext setRequestConfig
public void setRequestConfig(final RequestConfig config)
From source file:com.helger.httpclient.HttpClientHelper.java
@Nonnull public static HttpContext createHttpContext(@Nullable final HttpHost aProxy, @Nullable final Credentials aProxyCredentials) { final HttpClientContext ret = HttpClientContext.create(); if (aProxy != null) { ret.setRequestConfig(RequestConfig.custom().setProxy(aProxy).build()); if (aProxyCredentials != null) { final CredentialsProvider aCredentialsProvider = new BasicCredentialsProvider(); aCredentialsProvider.setCredentials(new AuthScope(aProxy), aProxyCredentials); ret.setCredentialsProvider(aCredentialsProvider); }/*from ww w. jav a 2 s . c o m*/ } return ret; }
From source file:com.mirth.connect.client.core.ConnectServiceUtil.java
public static void registerUser(String serverId, String mirthVersion, User user, String[] protocols, String[] cipherSuites) throws ClientException { CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; NameValuePair[] params = { new BasicNameValuePair("serverId", serverId), new BasicNameValuePair("version", mirthVersion), new BasicNameValuePair("user", ObjectXMLSerializer.getInstance().serialize(user)) }; HttpPost post = new HttpPost(); post.setURI(URI.create(URL_CONNECT_SERVER + URL_REGISTRATION_SERVLET)); post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8"))); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT) .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build(); try {/*from w w w . j a v a 2 s .com*/ HttpClientContext postContext = HttpClientContext.create(); postContext.setRequestConfig(requestConfig); httpClient = getClient(protocols, cipherSuites); httpResponse = httpClient.execute(post, postContext); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_MOVED_TEMPORARILY)) { throw new Exception("Failed to connect to update server: " + statusLine); } } catch (Exception e) { throw new ClientException(e); } finally { HttpClientUtils.closeQuietly(httpResponse); HttpClientUtils.closeQuietly(httpClient); } }
From source file:com.mirth.connect.client.core.ConnectServiceUtil.java
public static boolean sendStatistics(String serverId, String mirthVersion, boolean server, String data, String[] protocols, String[] cipherSuites) { if (data == null) { return false; }// w w w .j ava2 s .com boolean isSent = false; CloseableHttpClient client = null; HttpPost post = new HttpPost(); CloseableHttpResponse response = null; NameValuePair[] params = { new BasicNameValuePair("serverId", serverId), new BasicNameValuePair("version", mirthVersion), new BasicNameValuePair("server", Boolean.toString(server)), new BasicNameValuePair("data", data) }; RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT) .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build(); post.setURI(URI.create(URL_CONNECT_SERVER + URL_USAGE_SERVLET)); post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8"))); try { HttpClientContext postContext = HttpClientContext.create(); postContext.setRequestConfig(requestConfig); client = getClient(protocols, cipherSuites); response = client.execute(post, postContext); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if ((statusCode == HttpStatus.SC_OK)) { isSent = true; } } catch (Exception e) { } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(client); } return isSent; }
From source file:com.mirth.connect.client.core.ConnectServiceUtil.java
public static int getNotificationCount(String serverId, String mirthVersion, Map<String, String> extensionVersions, Set<Integer> archivedNotifications, String[] protocols, String[] cipherSuites) {/*from w w w. j ava 2 s . c o m*/ CloseableHttpClient client = null; HttpPost post = new HttpPost(); CloseableHttpResponse response = null; int notificationCount = 0; try { ObjectMapper mapper = new ObjectMapper(); String extensionVersionsJson = mapper.writeValueAsString(extensionVersions); NameValuePair[] params = { new BasicNameValuePair("op", NOTIFICATION_COUNT_GET), new BasicNameValuePair("serverId", serverId), new BasicNameValuePair("version", mirthVersion), new BasicNameValuePair("extensionVersions", extensionVersionsJson) }; RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT) .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build(); post.setURI(URI.create(URL_CONNECT_SERVER + URL_NOTIFICATION_SERVLET)); post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8"))); HttpClientContext postContext = HttpClientContext.create(); postContext.setRequestConfig(requestConfig); client = getClient(protocols, cipherSuites); response = client.execute(post, postContext); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if ((statusCode == HttpStatus.SC_OK)) { HttpEntity responseEntity = response.getEntity(); Charset responseCharset = null; try { responseCharset = ContentType.getOrDefault(responseEntity).getCharset(); } catch (Exception e) { responseCharset = ContentType.TEXT_PLAIN.getCharset(); } List<Integer> notificationIds = mapper.readValue( IOUtils.toString(responseEntity.getContent(), responseCharset).trim(), new TypeReference<List<Integer>>() { }); for (int id : notificationIds) { if (!archivedNotifications.contains(id)) { notificationCount++; } } } } catch (Exception e) { } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(client); } return notificationCount; }
From source file:com.mirth.connect.client.core.ConnectServiceUtil.java
public static List<Notification> getNotifications(String serverId, String mirthVersion, Map<String, String> extensionVersions, String[] protocols, String[] cipherSuites) throws Exception { CloseableHttpClient client = null;/* ww w.j av a2 s . c o m*/ HttpPost post = new HttpPost(); CloseableHttpResponse response = null; List<Notification> allNotifications = new ArrayList<Notification>(); try { ObjectMapper mapper = new ObjectMapper(); String extensionVersionsJson = mapper.writeValueAsString(extensionVersions); NameValuePair[] params = { new BasicNameValuePair("op", NOTIFICATION_GET), new BasicNameValuePair("serverId", serverId), new BasicNameValuePair("version", mirthVersion), new BasicNameValuePair("extensionVersions", extensionVersionsJson) }; RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT) .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build(); post.setURI(URI.create(URL_CONNECT_SERVER + URL_NOTIFICATION_SERVLET)); post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8"))); HttpClientContext postContext = HttpClientContext.create(); postContext.setRequestConfig(requestConfig); client = getClient(protocols, cipherSuites); response = client.execute(post, postContext); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if ((statusCode == HttpStatus.SC_OK)) { HttpEntity responseEntity = response.getEntity(); Charset responseCharset = null; try { responseCharset = ContentType.getOrDefault(responseEntity).getCharset(); } catch (Exception e) { responseCharset = ContentType.TEXT_PLAIN.getCharset(); } String responseContent = IOUtils.toString(responseEntity.getContent(), responseCharset).trim(); JsonNode rootNode = mapper.readTree(responseContent); for (JsonNode childNode : rootNode) { Notification notification = new Notification(); notification.setId(childNode.get("id").asInt()); notification.setName(childNode.get("name").asText()); notification.setDate(childNode.get("date").asText()); notification.setContent(childNode.get("content").asText()); allNotifications.add(notification); } } else { throw new ClientException("Status code: " + statusCode); } } catch (Exception e) { throw e; } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(client); } return allNotifications; }
From source file:com.aliyun.oss.common.comm.TimeoutServiceClient.java
@Override public ResponseMessage sendRequestCore(ServiceClient.Request request, ExecutionContext context) throws IOException { HttpRequestBase httpRequest = httpRequestFactory.createHttpRequest(request, context); HttpClientContext httpContext = HttpClientContext.create(); httpContext.setRequestConfig(this.requestConfig); CloseableHttpResponse httpResponse = null; HttpRequestTask httpRequestTask = new HttpRequestTask(httpRequest, httpContext); Future<CloseableHttpResponse> future = executor.submit(httpRequestTask); try {//from www.ja v a2 s . c o m httpResponse = future.get(this.config.getRequestTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { logException("[ExecutorService]The current thread was interrupted while waiting: ", e); httpRequest.abort(); throw new ClientException(e.getMessage(), e); } catch (ExecutionException e) { RuntimeException ex; httpRequest.abort(); if (e.getCause() instanceof IOException) { ex = ExceptionFactory.createNetworkException((IOException) e.getCause()); } else { ex = new OSSException(e.getMessage(), e); } logException("[ExecutorService]The computation threw an exception: ", ex); throw ex; } catch (TimeoutException e) { logException("[ExecutorService]The wait " + this.config.getRequestTimeout() + " timed out: ", e); httpRequest.abort(); throw new ClientException(e.getMessage(), OSSErrorCode.REQUEST_TIMEOUT, "Unknown", e); } return buildResponse(request, httpResponse); }
From source file:com.aliyun.oss.common.comm.DefaultServiceClient.java
protected HttpClientContext createHttpContext() { HttpClientContext httpContext = HttpClientContext.create(); httpContext.setRequestConfig(this.requestConfig); if (this.credentialsProvider != null) { httpContext.setCredentialsProvider(this.credentialsProvider); httpContext.setAuthCache(this.authCache); }//from www . ja v a 2s. c o m return httpContext; }
From source file:com.aliyun.oss.common.comm.DefaultServiceClient.java
@Override public ResponseMessage sendRequestCore(ServiceClient.Request request, ExecutionContext context) throws IOException { HttpRequestBase httpRequest = httpRequestFactory.createHttpRequest(request, context); setProxyAuthorizationIfNeed(httpRequest); HttpClientContext httpContext = createHttpContext(); httpContext.setRequestConfig(this.requestConfig); CloseableHttpResponse httpResponse = null; try {//w w w . ja v a 2s . c o m httpResponse = httpClient.execute(httpRequest, httpContext); } catch (IOException ex) { httpRequest.abort(); throw ExceptionFactory.createNetworkException(ex); } return buildResponse(request, httpResponse); }
From source file:org.nuxeo.connect.registration.RegistrationHelper.java
protected static HttpClientContext getHttpClientContext(String url, String login, String password) { HttpClientContext context = HttpClientContext.create(); // Set credentials provider CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (login != null) { Credentials ba = new UsernamePasswordCredentials(login, password); credentialsProvider.setCredentials(AuthScope.ANY, ba); }//from w w w. j a v a 2s . c om context.setCredentialsProvider(credentialsProvider); // Create AuthCache instance for preemptive authentication AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); try { authCache.put(URIUtils.extractHost(new URI(url)), basicAuth); } catch (URISyntaxException e) { throw new RuntimeException(e); } context.setAuthCache(authCache); // Create request configuration RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setConnectTimeout(10000); // Configure the http proxy if needed ProxyHelper.configureProxyIfNeeded(requestConfigBuilder, credentialsProvider, url); context.setRequestConfig(requestConfigBuilder.build()); return context; }
From source file:org.attribyte.api.http.impl.commons.Commons4Client.java
@Override public Response send(Request request, RequestOptions options) throws IOException { HttpUriRequest commonsRequest = null; switch (request.getMethod()) { case GET://from w w w.j av a 2 s.c o m commonsRequest = new HttpGet(request.getURI()); break; case DELETE: commonsRequest = new HttpDelete(request.getURI()); break; case HEAD: commonsRequest = new HttpHead(request.getURI()); break; case POST: { HttpEntityEnclosingRequestBase entityEnclosingRequest = new HttpPost(request.getURI()); commonsRequest = entityEnclosingRequest; EntityBuilder entityBuilder = EntityBuilder.create(); if (request.getBody() != null) { entityBuilder.setBinary(request.getBody().toByteArray()); } else { Collection<Parameter> parameters = request.getParameters(); List<NameValuePair> nameValuePairs = Lists.newArrayListWithExpectedSize(parameters.size()); for (Parameter parameter : parameters) { String[] values = parameter.getValues(); for (String value : values) { nameValuePairs.add(new BasicNameValuePair(parameter.getName(), value)); } } } entityEnclosingRequest.setEntity(entityBuilder.build()); break; } case PUT: { HttpEntityEnclosingRequestBase entityEnclosingRequest = new HttpPut(request.getURI()); commonsRequest = entityEnclosingRequest; EntityBuilder entityBuilder = EntityBuilder.create(); if (request.getBody() != null) { entityBuilder.setBinary(request.getBody().toByteArray()); } entityEnclosingRequest.setEntity(entityBuilder.build()); break; } } Collection<Header> headers = request.getHeaders(); for (Header header : headers) { String[] values = header.getValues(); for (String value : values) { commonsRequest.setHeader(header.getName(), value); } } ResponseBuilder builder = new ResponseBuilder(); CloseableHttpResponse response = null; InputStream is = null; try { if (options.followRedirects != RequestOptions.DEFAULT_FOLLOW_REDIRECTS) { RequestConfig localConfig = RequestConfig.copy(defaultRequestConfig) .setRedirectsEnabled(options.followRedirects) .setMaxRedirects(options.followRedirects ? 5 : 0).build(); HttpClientContext localContext = HttpClientContext.create(); localContext.setRequestConfig(localConfig); response = httpClient.execute(commonsRequest, localContext); } else { response = httpClient.execute(commonsRequest); } builder.setStatusCode(response.getStatusLine().getStatusCode()); for (org.apache.http.Header header : response.getAllHeaders()) { builder.addHeader(header.getName(), header.getValue()); } HttpEntity entity = response.getEntity(); if (entity != null) { is = entity.getContent(); if (is != null) { builder.setBody(Request.bodyFromInputStream(is, options.maxResponseBytes)); } } } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { //TODO? } } if (response != null) { response.close(); } } return builder.create(); }