public Map<String, String> connect(String url, Map<String, Object> parameters) throws ManagerResponseException { Map<String, String> response = new HashMap<String, String>(); CloseableHttpClient httpclient = HttpClients.createDefault(); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("j_username", (String) parameters.get("login"))); nvps.add(new BasicNameValuePair("j_password", (String) parameters.get("password"))); localContext = HttpClientContext.create(); localContext.setCookieStore(new BasicCookieStore()); HttpPost httpPost = new HttpPost(url); try { httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext); ResponseHandler<String> handler = new CustomResponseErrorHandler(); String body = handler.handleResponse(httpResponse); response.put(BODY, body); httpResponse.close(); } catch (Exception e) { authentificationUtils.getMap().clear(); throw new ManagerResponseException(e.getMessage(), e); } return response; }
/** * sendGetCommand * * @param url * @param parameters * @return */ public Map<String, String> sendGetCommand(String url, Map<String, Object> parameters) throws ManagerResponseException { Map<String, String> response = new HashMap<String, String>(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(url); try { CloseableHttpResponse httpResponse = httpclient.execute(httpget, localContext); ResponseHandler<String> handler = new CustomResponseErrorHandler(); String body = handler.handleResponse(httpResponse); response.put(BODY, body); httpResponse.close(); } catch (Exception e) { throw new ManagerResponseException(e.getMessage(), e); } return response; }
/** * sendDeleteCommand * * @param url * @return */ public Map<String, String> sendDeleteCommand(String url, Map<String, Object> credentials) throws ManagerResponseException { Map<String, String> response = new HashMap<String, String>(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpDelete httpDelete = new HttpDelete(url); CloseableHttpResponse httpResponse; try { httpResponse = httpclient.execute(httpDelete, localContext); ResponseHandler<String> handler = new CustomResponseErrorHandler(); String body = handler.handleResponse(httpResponse); response.put("body", body); httpResponse.close(); } catch (Exception e) { throw new ManagerResponseException(e.getMessage(), e); } return response; }
@Test public void testHttpRequestGet() throws Exception { RequestConfig.Builder req = RequestConfig.custom(); req.setConnectTimeout(5000); req.setConnectionRequestTimeout(5000); req.setRedirectsEnabled(false); req.setSocketTimeout(5000); req.setExpectContinueEnabled(false); HttpGet get = new HttpGet("http://127.0.0.1:54322/login"); get.setConfig(req.build()); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setDefaultMaxPerRoute(5); HttpClientBuilder builder = HttpClients.custom(); builder.disableAutomaticRetries(); builder.disableRedirectHandling(); builder.setConnectionTimeToLive(5, TimeUnit.SECONDS); builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE); builder.setConnectionManager(cm); CloseableHttpClient client = builder.build(); String s = client.execute(get, new ResponseHandler<String>() { @Override public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { assertEquals(301, response.getStatusLine().getStatusCode()); return "success"; } }); assertEquals("success", s); }
/** * sendPostCommand * * @param url * @param credentials * @param entity * @return * @throws ClientProtocolException */ public Map<String, Object> sendPostCommand(String url, Map<String, Object> credentials, String entity) throws ManagerResponseException { Map<String, Object> response = new HashMap<String, Object>(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); try { StringEntity stringEntity = new StringEntity(entity); httpPost.setEntity(stringEntity); CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext); ResponseHandler<String> handler = new CustomResponseErrorHandler(); String body = handler.handleResponse(httpResponse); response.put(BODY, body); httpResponse.close(); } catch (Exception e) { throw new ManagerResponseException(e.getMessage(), e); } return response; }
/** * sendPutCommand * * @param url * @param parameters * @return * @throws ClientProtocolException */ public Map<String, Object> sendPutCommand(String url, Map<String, Object> credentials, Map<String, String> parameters) throws ManagerResponseException { Map<String, Object> response = new HashMap<String, Object>(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPut httpPut = new HttpPut(url); httpPut.setHeader("Accept", "application/json"); httpPut.setHeader("Content-type", "application/json"); try { ObjectMapper mapper = new ObjectMapper(); StringEntity entity = new StringEntity(mapper.writeValueAsString(parameters)); httpPut.setEntity(entity); CloseableHttpResponse httpResponse = httpclient.execute(httpPut, localContext); ResponseHandler<String> handler = new CustomResponseErrorHandler(); String body = handler.handleResponse(httpResponse); response.put(BODY, body); httpResponse.close(); } catch (Exception e) { throw new ManagerResponseException(e.getMessage(), e); } return response; }
/** * sendGetCommand * * @param url * @param log * @return * @throws MojoExecutionException * @throws CheckException */ public Map<String, String> sendGetCommand( String url, Log log ) throws CheckException { Map<String, String> response = new HashMap<String, String>(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet( url ); try { CloseableHttpResponse httpResponse = httpclient.execute( httpget, localContext ); ResponseHandler<String> handler = new ResponseErrorHandler(); String body = handler.handleResponse( httpResponse ); response.put( "body", body ); httpResponse.close(); } catch ( Exception e ) { log.warn( "GET request failed!" ); throw new CheckException( "Send GET to server failed!", e ); } return response; }
public static <T> T execute(HttpUriRequest request,ResponseHandler<T> responseHandler){ String uriId = loggerRequest(request); if(responseHandler instanceof LocalResponseHandler){ LocalResponseHandler lrh = (LocalResponseHandler) responseHandler; lrh.setUriId(uriId); } try { T t = httpClient.execute(request, responseHandler,HttpClientContext.create()); if(resultErrorHandler != null){ resultErrorHandler.doHandle(uriId, request, t); } return t; } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); } return null; }
/** * * @param mch_id mch_id * @param request request * @param clazz clazz * @param sign_type 数据返回验证签名类型 * @param key 数据返回验证签名key * @since 2.8.5 * @return result */ public static <T> T keyStoreExecuteXmlResult(String mch_id,HttpUriRequest request,Class<T> clazz,String sign_type,String key){ String uriId = loggerRequest(request); ResponseHandler<T> responseHandler = XmlResponseHandler.createResponseHandler(clazz,sign_type,key); if(responseHandler instanceof LocalResponseHandler){ LocalResponseHandler lrh = (LocalResponseHandler) responseHandler; lrh.setUriId(uriId); } try { T t = httpClient_mchKeyStore.get(mch_id).execute(request,responseHandler,HttpClientContext.create()); if(resultErrorHandler != null){ resultErrorHandler.doHandle(uriId, request, t); } return t; } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); } return null; }
public AccessTokenDTO getToken(String code) { DefaultHttpClient httpclient = new DefaultHttpClient(); AccessTokenDTO token = null; try { HttpPost httppost = new HttpPost("https://api.twitch.tv/kraken/oauth2/token" + "?client_id=" + Config.getCatalog().twitch.clientId + "&client_secret=" + Config.getCatalog().twitch.clientSecret + "&code=" + code + "&grant_type=authorization_code" + "&redirect_uri=" + Config.getCatalog().twitch.redirectUri); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); token = new Gson().fromJson(responseBody, AccessTokenDTO.class); } catch (IOException e) { TwasiLogger.log.error(e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); httpclient.close(); } return token; }
public static Optional<String> getResponseAsString(HttpRequestBase httpRequest, HttpClient client) { Optional<String> result = Optional.empty(); final int waitTime = 60000; try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(waitTime).setConnectTimeout(waitTime) .setConnectionRequestTimeout(waitTime).build(); httpRequest.setConfig(requestConfig); result = Optional.of(client.execute(httpRequest, responseHandler)); } catch (HttpResponseException httpResponseException) { LOG.error("getResponseAsString(): caught 'HttpResponseException' while processing request <{}> :=> <{}>", httpRequest, httpResponseException.getMessage()); } catch (IOException ioe) { LOG.error("getResponseAsString(): caught 'IOException' while processing request <{}> :=> <{}>", httpRequest, ioe.getMessage()); } finally { httpRequest.releaseConnection(); } return result; }
@Override public <T> T execute(HttpHost host, HttpRequest request, ResponseHandler<? extends T> handler, HttpContext context) throws IOException { HttpResponse response = execute(host, request, context); try { return handler.handleResponse(response); } finally { consumeContentQuietly(response); } }
public SPARQL11SEProtocol(SPARQL11SEProperties properties) throws IllegalArgumentException { super(properties); if (properties == null) { logger.fatal("Properties are null"); throw new IllegalArgumentException("Properties are null"); } this.properties = properties; //Create secure HTTP client SSLConnectionSocketFactory sslSocketFactory = getSSLConnectionSocketFactory(); if (sslSocketFactory != null) httpclient = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build(); //Create WebSocket clients (secure and not) wsClient = new WebsocketClientEndpoint(properties.getSubscribeScheme()+"://"+properties.getHost()+":"+properties.getSubscribePort()+properties.getSubscribePath()); wssClient = new SecureWebsocketClientEndpoint(properties.getSecureSubscribeScheme()+"://"+properties.getHost()+":"+properties.getSecureSubscribePort()+properties.getSecureSubscribePath()); //HTTP response handler responseHandler = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse response) { String body = null; HttpEntity entity = response.getEntity(); try { body = EntityUtils.toString(entity,Charset.forName("UTF-8")); } catch (ParseException e) { body = e.getMessage(); } catch (IOException e) { body = e.getMessage(); } return body; } }; }
private static File fetchSchema(URL url, final Path tempFile) throws URISyntaxException, IOException { System.out.printf("Fetching remote schema <%s>%n", url); final Properties buildProperties = getBuildProperties(); final HttpClientBuilder clientBuilder = HttpClientBuilder.create() .setUserAgent( String.format("%s:%s/%s (%s)", buildProperties.getProperty("groupId", "unknown"), buildProperties.getProperty("artifactId", "unknown"), buildProperties.getProperty("version", "unknown"), buildProperties.getProperty("name", "unknown")) ); try (CloseableHttpClient client = clientBuilder.build()) { final HttpUriRequest request = RequestBuilder.get() .setUri(url.toURI()) .setHeader(HttpHeaders.ACCEPT, getAcceptHeaderValue()) .build(); return client.execute(request, new ResponseHandler<File>() { @Override public File handleResponse(HttpResponse response) throws IOException { final File cf = tempFile.toFile(); FileUtils.copyInputStreamToFile(response.getEntity().getContent(), cf); return cf; } }); } }
public void applyUserInfo(TwitchAccount account) { DefaultHttpClient httpclient = new DefaultHttpClient(); TwitchAccount acc = null; try { HttpGet httpget = new HttpGet("https://api.twitch.tv/kraken/user"); httpget.setHeader("Accept", "application/vnd.twitchtv.v5+json"); httpget.setHeader("Authorization", "OAuth " + account.getToken().getAccessToken()); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); System.out.println(responseBody); UserInfoDTO info = new Gson().fromJson(responseBody, UserInfoDTO.class); account.setEmail(info.getEmail()); } catch (IOException e) { TwasiLogger.log.error(e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); httpclient.close(); } }
@Override public String execute(HttpUriRequest post, ResponseHandler handler) { try { InputStream contStream = ((HttpEntityEnclosingRequest) post).getEntity().getContent(); try (BufferedReader buffer = new BufferedReader(new InputStreamReader(contStream))) { this.setRegData(URLDecoder.decode(buffer.readLine(), "UTF-8")); } } catch (UnsupportedOperationException | IOException e) { // Never happens - simulated return "ERR"; } return "OK"; }
private static ResponseHandler<String> getStringResponseHandler() { return response -> { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity, "UTF-8") : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } }; }
/** * @param url * @param parameters * @param log * @return * @throws MojoExecutionException */ public Map<String, String> connect( String url, Map<String, Object> parameters, Log log ) throws MojoExecutionException { Map<String, String> response = new HashMap<String, String>(); CloseableHttpClient httpclient = HttpClients.createDefault(); List<NameValuePair> nvps = new ArrayList<>(); nvps.add( new BasicNameValuePair( "j_username", (String) parameters.get( "login" ) ) ); nvps.add( new BasicNameValuePair( "j_password", (String) parameters.get( "password" ) ) ); localContext = HttpClientContext.create(); localContext.setCookieStore( new BasicCookieStore() ); HttpPost httpPost = new HttpPost( url ); try { httpPost.setEntity( new UrlEncodedFormEntity( nvps ) ); CloseableHttpResponse httpResponse = httpclient.execute( httpPost, localContext ); ResponseHandler<String> handler = new ResponseErrorHandler(); String body = handler.handleResponse( httpResponse ); response.put( "body", body ); httpResponse.close(); isConnected = true; log.info( "Connection successful" ); } catch ( Exception e ) { log.error( "Connection failed! : " + e.getMessage() ); isConnected = false; throw new MojoExecutionException( "Connection failed, please check your manager location or your credentials" ); } return response; }
/** * @param url * @param parameters * @return * @throws MojoExecutionException * @throws CheckException */ public Map<String, Object> sendPostCommand( String url, Map<String, String> parameters, Log log ) throws CheckException { Map<String, Object> response = new HashMap<String, Object>(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost( url ); httpPost.setHeader( "Accept", "application/json" ); httpPost.setHeader( "Content-type", "application/json" ); try { ObjectMapper mapper = new ObjectMapper(); StringEntity entity = new StringEntity( mapper.writeValueAsString( parameters ) ); httpPost.setEntity( entity ); CloseableHttpResponse httpResponse = httpclient.execute( httpPost, localContext ); ResponseHandler<String> handler = new ResponseErrorHandler(); String body = handler.handleResponse( httpResponse ); response.put( "body", body ); httpResponse.close(); } catch ( Exception e ) { log.warn( "POST request failed!" ); throw new CheckException( "Send POST to server failed!", e ); } return response; }
private String executeGetRequest(String url) throws IOException { RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(15000) .setSocketTimeout(15000) .build(); HttpGet method = new HttpGet(url); method.setConfig(requestConfig); try (CloseableHttpClient client = HttpClients.createDefault()) { ResponseHandler<String> responseHandler = new BasicResponseHandler(); return client.execute(method, responseHandler); } }
/** * Resolves the latest available Airsonic version by inspecting github. */ private void readLatestVersion() throws IOException { LOG.debug("Starting to read latest version"); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(10000) .setSocketTimeout(10000) .build(); HttpGet method = new HttpGet(VERSION_URL + "?v=" + getLocalVersion()); method.setConfig(requestConfig); String content; try (CloseableHttpClient client = HttpClients.createDefault()) { ResponseHandler<String> responseHandler = new BasicResponseHandler(); content = client.execute(method, responseHandler); } List<String> unsortedTags = JsonPath.read(content, JSON_PATH); Function<String, Version> convertToVersion = s -> { Matcher match = VERSION_REGEX.matcher(s); if(!match.matches()) { throw new RuntimeException("Unexpected tag format " + s); } return new Version(match.group(1)); }; Predicate<Version> finalVersionPredicate = version -> !version.isPreview(); Optional<Version> betaV = unsortedTags.stream().map(convertToVersion).sorted(Comparator.reverseOrder()).findFirst(); Optional<Version> finalV = unsortedTags.stream().map(convertToVersion).sorted(Comparator.reverseOrder()).filter(finalVersionPredicate).findFirst(); LOG.debug("Got {} for beta version", betaV); LOG.debug("Got {} for final version", finalV); latestBetaVersion = betaV.get(); latestFinalVersion = finalV.get(); }
private String[] executeRequest(HttpUriRequest request) throws IOException { try (CloseableHttpClient client = HttpClients.createDefault()) { ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = client.execute(request, responseHandler); return response.split("\\n"); } }
public TwitchAccount getTwitchAccountByToken(AccessTokenDTO token) { DefaultHttpClient httpclient = new DefaultHttpClient(); TwitchAccount acc = null; try { HttpGet httpget = new HttpGet("https://api.twitch.tv/kraken"); httpget.setHeader("Accept", "application/vnd.twitchtv.v5+json"); httpget.setHeader("Authorization", "OAuth " + token.getAccessToken()); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); TokenInfoDTO info = new Gson().fromJson(responseBody, TokenInfoDTO.class); acc = new TwitchAccount(info.getToken().getUserName(), token.toModel(), info.getToken().getUserId(), new ArrayList<>()); acc.setEmail(info.getToken().getEmail()); } catch (IOException e) { TwasiLogger.log.error(e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); httpclient.close(); } return acc; }
static <R> ResponseHandler<R> ignoreResponseBodyHandler() { return new ResponseHandler<R>() { @Override public R handleResponse(HttpResponse response) throws IOException { assert2xx(response); return null; } }; }
static <R> ResponseHandler<R> readResponseBodyHandler( final Class<R> responseType) { return new ResponseHandler<R>() { @Override public R handleResponse(HttpResponse response) throws IOException { return readResponseBody(response, responseType); } }; }
@Override public <T> T execute(final HttpUriRequest request, final ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException { Subsegment subsegment = recorder.beginSubsegment(determineTarget(request).getHostName()); return wrapHttpSupplier(subsegment, () -> { if (null != subsegment) { TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(request)); } TracedResponseHandler<? extends T> wrappedHandler = new TracedResponseHandler<>(responseHandler); T response = wrappedClient.execute(request, wrappedHandler); return response; }); }
@Override public <T> T execute(final HttpHost target, final HttpRequest request, final ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException { Subsegment subsegment = recorder.beginSubsegment(target.getHostName()); return wrapHttpSupplier(subsegment, () -> { if (null != subsegment) { TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(target, request)); } TracedResponseHandler<? extends T> wrappedHandler = new TracedResponseHandler<>(responseHandler); T response = wrappedClient.execute(target, request, wrappedHandler); return response; }); }
@Override public <T> T execute(final HttpHost target, final HttpRequest request, final ResponseHandler<? extends T> responseHandler, final HttpContext context) throws IOException, ClientProtocolException { Subsegment subsegment = recorder.beginSubsegment(target.getHostName()); return wrapHttpSupplier(subsegment, () -> { if (null != subsegment) { TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(target, request)); } TracedResponseHandler<? extends T> wrappedHandler = new TracedResponseHandler<>(responseHandler); T response = wrappedClient.execute(target, request, wrappedHandler, context); return response; }); }
public <T> T execute( final HttpUriRequest request, final ResponseHandler<? extends T> responseHandler, final HttpContext context) throws IOException, ClientProtocolException { HttpHost target = determineTarget(request); return execute(target, request, responseHandler, context); }
public <T> T execute( final HttpHost target, final HttpRequest request, final ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException { return execute(target, request, responseHandler, null); }
public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context) throws IOException, ClientProtocolException { HttpResponse response = execute(target, request, context); try { return responseHandler.handleResponse(response); } finally { HttpEntity entity = response.getEntity(); if (entity != null) EntityUtils.consume(entity); } }
@Override public <T> T execute(final HttpRequestBase request, final ResponseHandler<T> responseHandler) throws IOException { if(StringUtils.isNotBlank(request.getURI().getRawQuery())) { request.setURI(URI.create(String.format("%s%s?%s", uri, request.getURI().getRawPath(), request.getURI().getRawQuery()))); } else { request.setURI(URI.create(String.format("%s%s", uri, request.getURI().getRawPath()))); } return super.execute(request, responseHandler); }
/** * 执行请求 * * @date 2015年7月17日 * @param responseHandler * @return */ public <T> T execute(final ResponseHandler<? extends T> responseHandler) { settingRequest(); if (httpClient == null) httpClient = clientBuilder.build(); try { return httpClient.execute(request, responseHandler); } catch (IOException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } }
private <T> T a(HttpUriRequest httpUriRequest, ResponseHandler<? extends T> responseHandler) throws Exception { try { return this.c.execute(httpUriRequest, responseHandler); } catch (Throwable e) { throw new Exception(e); } }
private <T> T a(HttpUriRequest httpUriRequest, ResponseHandler<? extends T> responseHandler, HttpContext httpContext) throws Exception { try { return this.c.execute(httpUriRequest, responseHandler, httpContext); } catch (Throwable e) { throw new Exception(e); } }
private <T> T a(HttpHost httpHost, HttpRequest httpRequest, ResponseHandler<? extends T> responseHandler) throws Exception { try { return this.c.execute(httpHost, httpRequest, responseHandler); } catch (Throwable e) { throw new Exception(e); } }
private <T> T a(HttpHost httpHost, HttpRequest httpRequest, ResponseHandler<? extends T> responseHandler, HttpContext httpContext) throws Exception { try { return this.c.execute(httpHost, httpRequest, responseHandler, httpContext); } catch (Throwable e) { throw new Exception(e); } }
@Override public <T> T execute(HttpUriRequest arg0, ResponseHandler<? extends T> arg1) { throw new UnsupportedOperationException(); }
@Override public <T> T execute(HttpUriRequest arg0, ResponseHandler<? extends T> arg1, HttpContext arg2) { throw new UnsupportedOperationException(); }