List of usage examples for org.apache.http.client.config RequestConfig custom
public static RequestConfig.Builder custom()
From source file:com.codeabovelab.dm.gateway.proxy.common.BalancerConfiguration.java
protected CloseableHttpClient configuredHttpClient(HttpClientBuilder httpClientBuilder) { LOG.info("HttpClient settings: maxConnections: {}, socketTimeout: {}, connectTimeout: {}", maxConnections, socketTimeout, connectTimeout); return httpClientBuilder.setMaxConnPerRoute(maxConnections).setMaxConnTotal(maxConnections) .setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(socketTimeout) .setConnectTimeout(connectTimeout).build()) .disableCookieManagement().build(); }
From source file:com.zxy.commons.httpclient.HttpclientUtils.java
/** * Post url/* w ww .j a v a2 s .c o m*/ * * @param connectTimeoutSec () * @param socketTimeoutSec ??() * @param url url? * @param params {@link org.apache.http.NameValuePair} params * <p> * example:{@code params.add(new BasicNameValuePair("id", "123456"));} * @return post?? * @throws ClientProtocolException ClientProtocolException * @throws IOException IOException * @see org.apache.http.NameValuePair * @see org.apache.http.message.BasicNameValuePair */ public static String post(int connectTimeoutSec, int socketTimeoutSec, String url, List<NameValuePair> params) throws ClientProtocolException, IOException { CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; try { // httpClient = HttpClients.createDefault(); RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeoutSec * 1000) .setConnectionRequestTimeout(connectTimeoutSec * 1000).setSocketTimeout(socketTimeoutSec * 1000) .build(); httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); HttpPost httppost = new HttpPost(url); UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(params, Charsets.UTF_8); httppost.setEntity(uefEntity); httpResponse = httpClient.execute(httppost); HttpEntity entity = httpResponse.getEntity(); return EntityUtils.toString(entity, Charsets.UTF_8); } finally { HttpClientUtils.closeQuietly(httpResponse); HttpClientUtils.closeQuietly(httpClient); } }
From source file:com.tremolosecurity.unison.proxy.auth.twitter.TwitterAuth.java
public void doGet(HttpServletRequest request, HttpServletResponse response, AuthStep as) throws IOException, ServletException { HttpSession session = ((HttpServletRequest) request).getSession(); HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session .getAttribute(ProxyConstants.AUTH_MECH_PARAMS); ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ); MyVDConnection myvd = cfg.getMyVD(); String consumerKey = authParams.get("consumerKey").getValues().get(0); String consumerSecret = authParams.get("consumerSecret").getValues().get(0); String accessToken = authParams.get("accessToken").getValues().get(0); String accessSecret = authParams.get("accessSecret").getValues().get(0); boolean linkToDirectory = Boolean.parseBoolean(authParams.get("linkToDirectory").getValues().get(0)); String noMatchOU = authParams.get("noMatchOU").getValues().get(0); String uidAttr = authParams.get("uidAttr").getValues().get(0); String lookupFilter = authParams.get("lookupFilter").getValues().get(0); //String userLookupClassName = authParams.get("userLookupClassName").getValues().get(0); UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG); RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder(); URL reqURL = new URL(request.getRequestURL().toString()); String redirectURL = reqURL.getProtocol() + "://" + reqURL.getHost(); if (reqURL.getPort() != -1) { redirectURL += ":" + reqURL.getPort(); }/*from www . j a va2s. c om*/ String urlChain = holder.getUrl().getAuthChain(); AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName()); AuthMechType amt = act.getAuthMech().get(as.getId()); String authMechName = amt.getName(); redirectURL += cfg.getAuthMechs().get(authMechName).getUri(); if (request.getParameter("oauth_verifier") == null) { BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager( GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry()); RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build(); CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc) .build(); HttpPost post = new HttpPost("https://api.twitter.com/oauth/request_token"); this.signRequest(post, "", accessToken, accessSecret, consumerKey, consumerSecret); CloseableHttpResponse httpResp = http.execute(post); BufferedReader in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent())); StringBuffer token = new StringBuffer(); String line = null; while ((line = in.readLine()) != null) { token.append(line); } httpResp.close(); bhcm.close(); System.err.println(token); List<NameValuePair> parsed = URLEncodedUtils.parse(token.toString(), Charsets.UTF_8); HashMap<String, String> accessTokens = new HashMap<String, String>(); for (NameValuePair nvp : parsed) { accessTokens.put(nvp.getName(), nvp.getValue()); } request.getSession().setAttribute("twitterAccessToken", accessTokens); StringBuffer b = new StringBuffer().append("https://api.twitter.com/oauth/authenticate?oauth_token=") .append(accessTokens.get("oauth_token")); response.sendRedirect(b.toString()); } else { String oauthVerifier = request.getParameter("oauth_verifier"); HashMap<String, String> accessTokens = (HashMap<String, String>) request.getSession() .getAttribute("twitterAccessToken"); BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager( GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry()); RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build(); CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc) .build(); HttpUriRequest post = new HttpPost(); try { post = RequestBuilder.post().setUri(new java.net.URI("https://api.twitter.com/oauth/access_token")) .addParameter("oauth_verifier", oauthVerifier).build(); } catch (URISyntaxException e) { throw new ServletException("Could not create post request"); } this.signRequest(post, "oauth_verifier=" + oauthVerifier, accessTokens.get("oauth_token"), accessTokens.get("oauth_token_secret"), consumerKey, consumerSecret); CloseableHttpResponse httpResp = http.execute(post); BufferedReader in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent())); StringBuffer token = new StringBuffer(); String line = null; while ((line = in.readLine()) != null) { token.append(line); } EntityUtils.consumeQuietly(httpResp.getEntity()); httpResp.close(); System.err.println(token); List<NameValuePair> parsed = URLEncodedUtils.parse(token.toString(), Charsets.UTF_8); HashMap<String, String> userTokens = new HashMap<String, String>(); for (NameValuePair nvp : parsed) { userTokens.put(nvp.getName(), nvp.getValue()); } request.getSession().setAttribute("twitterUserToken", accessTokens); HttpGet get = new HttpGet( "https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true"); this.signRequest(get, "", userTokens.get("oauth_token"), userTokens.get("oauth_token_secret"), consumerKey, consumerSecret); httpResp = http.execute(get); in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent())); token.setLength(0); line = null; while ((line = in.readLine()) != null) { token.append(line); } EntityUtils.consumeQuietly(httpResp.getEntity()); httpResp.close(); System.err.println(token); httpResp.close(); bhcm.close(); Map attrs = com.cedarsoftware.util.io.JsonReader.jsonToMaps(token.toString()); if (!linkToDirectory) { loadUnlinkedUser(session, noMatchOU, uidAttr, act, attrs); as.setSuccess(true); } else { lookupUser(as, session, myvd, noMatchOU, uidAttr, lookupFilter, act, attrs); } String redirectToURL = request.getParameter("target"); if (redirectToURL != null && !redirectToURL.isEmpty()) { reqHolder.setURL(redirectToURL); } holder.getConfig().getAuthManager().nextAuth(request, response, session, false); } }
From source file:org.elasticsearch.xpack.watcher.common.http.HttpClient.java
public HttpResponse execute(HttpRequest request) throws IOException { URI uri = createURI(request); HttpRequestBase internalRequest;/*from w w w .j a v a2s .co m*/ if (request.method == HttpMethod.HEAD) { internalRequest = new HttpHead(uri); } else { HttpMethodWithEntity methodWithEntity = new HttpMethodWithEntity(uri, request.method.name()); if (request.hasBody()) { ByteArrayEntity entity = new ByteArrayEntity(request.body.getBytes(StandardCharsets.UTF_8)); String contentType = request.headers().get(HttpHeaders.CONTENT_TYPE); if (Strings.hasLength(contentType)) { entity.setContentType(contentType); } else { entity.setContentType(ContentType.TEXT_PLAIN.toString()); } methodWithEntity.setEntity(entity); } internalRequest = methodWithEntity; } internalRequest.setHeader(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.name()); // headers if (request.headers().isEmpty() == false) { for (Map.Entry<String, String> entry : request.headers.entrySet()) { internalRequest.setHeader(entry.getKey(), entry.getValue()); } } // BWC - hack for input requests made to elasticsearch that do not provide the right content-type header! if (request.hasBody() && internalRequest.containsHeader("Content-Type") == false) { XContentType xContentType = XContentFactory.xContentType(request.body()); if (xContentType != null) { internalRequest.setHeader("Content-Type", xContentType.mediaType()); } } RequestConfig.Builder config = RequestConfig.custom(); setProxy(config, request, settingsProxy); HttpClientContext localContext = HttpClientContext.create(); // auth if (request.auth() != null) { ApplicableHttpAuth applicableAuth = httpAuthRegistry.createApplicable(request.auth); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); applicableAuth.apply(credentialsProvider, new AuthScope(request.host, request.port)); localContext.setCredentialsProvider(credentialsProvider); // preemptive auth, no need to wait for a 401 first AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(new HttpHost(request.host, request.port, request.scheme.scheme()), basicAuth); localContext.setAuthCache(authCache); } // timeouts if (request.connectionTimeout() != null) { config.setConnectTimeout(Math.toIntExact(request.connectionTimeout.millis())); } else { config.setConnectTimeout(Math.toIntExact(defaultConnectionTimeout.millis())); } if (request.readTimeout() != null) { config.setSocketTimeout(Math.toIntExact(request.readTimeout.millis())); config.setConnectionRequestTimeout(Math.toIntExact(request.readTimeout.millis())); } else { config.setSocketTimeout(Math.toIntExact(defaultReadTimeout.millis())); config.setConnectionRequestTimeout(Math.toIntExact(defaultReadTimeout.millis())); } internalRequest.setConfig(config.build()); try (CloseableHttpResponse response = SocketAccess .doPrivileged(() -> client.execute(internalRequest, localContext))) { // headers Header[] headers = response.getAllHeaders(); Map<String, String[]> responseHeaders = new HashMap<>(headers.length); for (Header header : headers) { if (responseHeaders.containsKey(header.getName())) { String[] old = responseHeaders.get(header.getName()); String[] values = new String[old.length + 1]; System.arraycopy(old, 0, values, 0, old.length); values[values.length - 1] = header.getValue(); responseHeaders.put(header.getName(), values); } else { responseHeaders.put(header.getName(), new String[] { header.getValue() }); } } final byte[] body; // not every response has a content, i.e. 204 if (response.getEntity() == null) { body = new byte[0]; } else { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { try (InputStream is = new SizeLimitInputStream(maxResponseSize, response.getEntity().getContent())) { Streams.copy(is, outputStream); } body = outputStream.toByteArray(); } } return new HttpResponse(response.getStatusLine().getStatusCode(), body, responseHeaders); } }
From source file:org.azkfw.crawler.downloader.engine.SimpleDownloadEngine.java
/** * HTTP??//ww w .jav a 2 s . com * <p> * ???????HTTP????? * </p> * * @return HTTP */ private HttpClient defaultClient() { // Ver old //HttpClient httpClient = new DefaultHttpClient(); // Ver 4.3 // int socketTimeout = 3; // int connectionTimeout = 3; // RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeout).setSocketTimeout(socketTimeout).build(); RequestConfig requestConfig = RequestConfig.custom().build(); List<Header> headers = new ArrayList<Header>(); headers.add(new BasicHeader("Accept-Charset", "utf-8")); headers.add(new BasicHeader("Accept-Language", "ja, en;q=0.8")); // chrom headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.63 Safari/537.36")); HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig) .setDefaultHeaders(headers).build(); return httpClient; }
From source file:MainFrame.HttpCommunicator.java
public boolean removeLessons(JSONObject jsObj) throws MalformedURLException, IOException { String response = null;//from w w w . j a va 2s .c o m if (SingleDataHolder.getInstance().isProxyActivated) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword)); HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider) .build(); HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress, SingleDataHolder.getInstance().proxyPort); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php"); post.setConfig(config); StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("apideskviewer.getAllLessons", head); HttpEntity entity = builder.build(); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); System.out.println("responseBody : " + response); } else { HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php"); StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("apiDeskViewer.removeLesson", head); HttpEntity entity = builder.build(); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); System.out.println("responseBody : " + response); } if (response.equals(new String("\"success\""))) return true; else return false; }
From source file:com.frochr123.periodictasks.RefreshProjectorThread.java
public void updateProjectorImage() { if (!updateInProgress && !shutdownThreadRunning) { updateInProgress = true;//w w w. ja va 2s .c om new Thread() { @Override public void run() { try { if (VisicutModel.getInstance() != null && VisicutModel.getInstance().getSelectedLaserDevice() != null && VisicutModel.getInstance().getSelectedLaserDevice().getProjectorURL() != null && !VisicutModel.getInstance().getSelectedLaserDevice().getProjectorURL() .isEmpty()) { BufferedImage img = PreviewImageExport.generateImage(getProjectorWidth(), getProjectorHeight(), !isShutdownInProgress()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PreviewImageExport.writePngToOutputStream(outputStream, img); byte[] imagePostDataByte = outputStream.toByteArray(); // Create HTTP client and cusomized config for timeouts CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(DEFAULT_PROJECTOR_TIMEOUT) .setConnectTimeout(DEFAULT_PROJECTOR_TIMEOUT) .setConnectionRequestTimeout(DEFAULT_PROJECTOR_TIMEOUT).build(); // Create HTTP Post request HttpPost httpPost = new HttpPost( VisicutModel.getInstance().getSelectedLaserDevice().getProjectorURL()); httpPost.setConfig(requestConfig); // Insert file upload MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addBinaryBody("data", imagePostDataByte, ContentType.APPLICATION_OCTET_STREAM, "data"); HttpEntity httpEntity = multipartEntityBuilder.build(); httpPost.setEntity(httpEntity); // Set authentication information String encodedCredentials = Helper.getEncodedCredentials( VisicutModel.getInstance().getSelectedLaserDevice().getURLUser(), VisicutModel.getInstance().getSelectedLaserDevice().getURLPassword()); if (!encodedCredentials.isEmpty()) { httpPost.addHeader("Authorization", "Basic " + encodedCredentials); } // Send request CloseableHttpResponse res = httpClient.execute(httpPost); // React to possible server side errors if (res.getStatusLine() == null || res.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new Exception("Server sent wrong HTTP status code: " + new Integer(res.getStatusLine().getStatusCode()).toString()); } // Close everything correctly res.close(); httpClient.close(); } } // This is caused internally in apache commons library for wrong authentication // Would need to add additional apache commons library file to get a correct exception back for that catch (NoClassDefFoundError error) { // Set flag for exception handling, sleep and message lastExceptionMessage = "Projector thread exception: Authentication error!"; } catch (Exception e) { // Set flag for exception handling, sleep and message lastExceptionMessage = "Projector thread exception (2): " + e.getMessage(); } updateInProgress = false; // Need to check if shutdown is set here first, otherwise these asynchronous calls // would always overwrite a call to shutdown in progress = true if (shutdownInProgress) { shutdownInProgress = false; } } }.start(); } }
From source file:org.smssecure.smssecure.mms.LegacyMmsConnection.java
protected CloseableHttpClient constructHttpClient() throws IOException { RequestConfig config = RequestConfig.custom().setConnectTimeout(20 * 1000) .setConnectionRequestTimeout(20 * 1000).setSocketTimeout(20 * 1000).setMaxRedirects(20).build(); URL mmsc = new URL(apn.getMmsc()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); if (apn.hasAuthentication()) { credsProvider.setCredentials(//www . jav a 2 s. co m new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()), new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword())); } return HttpClients.custom().setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4()) .setRedirectStrategy(new LaxRedirectStrategy()) .setUserAgent(SilencePreferences.getMmsUserAgent(context, USER_AGENT)) .setConnectionManager(new BasicHttpClientConnectionManager()).setDefaultRequestConfig(config) .setDefaultCredentialsProvider(credsProvider).build(); }
From source file:org.wso2.carbon.bpmn.extensions.rest.RESTInvoker.java
private void configureHttpClient() { parseConfiguration();/* w w w . j a v a 2 s . c o m*/ RequestConfig defaultRequestConfig = RequestConfig.custom().setExpectContinueEnabled(true) .setConnectTimeout(connectionTimeout).setSocketTimeout(socketTimeout).build(); connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setDefaultMaxPerRoute(maxTotalConnectionsPerRoute); connectionManager.setMaxTotal(maxTotalConnections); client = HttpClients.custom().setConnectionManager(connectionManager) .setDefaultRequestConfig(defaultRequestConfig).build(); if (log.isDebugEnabled()) { log.debug("BPMN REST client initialized with" + "maxTotalConnection = " + maxTotalConnections + "maxConnectionsPerRoute = " + maxTotalConnectionsPerRoute + "connectionTimeout = " + connectionTimeout); } }
From source file:edu.usu.sdl.apiclient.AbstractService.java
protected APIResponse callAPI(String apiPath, Map<String, String> parameters) { APIResponse response = null;//from w w w . ja v a2s.co m try { RequestConfig defaultRequestConfig = RequestConfig.custom().setCircularRedirectsAllowed(true).build(); RequestBuilder builder = RequestBuilder.get().setUri(new URI(loginModel.getServerUrl() + apiPath)) .addHeader(CONTENT_TYPE, MEDIA_TYPE_JSON).setConfig(defaultRequestConfig); if (parameters != null) { for (String key : parameters.keySet()) { builder.addParameter(key, parameters.get(key)); } } HttpUriRequest request = builder.build(); try (CloseableHttpResponse httpResponse = getClient().execute(request)) { response = new APIResponse(); response.setResponseCode(httpResponse.getStatusLine().getStatusCode()); HttpEntity entity1 = httpResponse.getEntity(); StringBuilder data = new StringBuilder(); try (BufferedReader in = new BufferedReader(new InputStreamReader(entity1.getContent()))) { in.lines().forEach(line -> { data.append(line).append("\n"); }); } response.setResponseBody(data.toString()); EntityUtils.consume(entity1); } } catch (IOException | URISyntaxException ex) { throw new ConnectionException("Unable to Connect.", ex); } return response; }