public String getPage(String symbol) { String rtn = null; String url = String.format("https://finance.yahoo.com/quote/%s/?p=%s", symbol, symbol); HttpGet request = new HttpGet(url); System.out.println(url); request.addHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13"); try { HttpResponse response = client.execute(request, context); System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } rtn = result.toString(); HttpClientUtils.closeQuietly(response); } catch (Exception ex) { System.out.println("Exception"); System.out.println(ex); } System.out.println("returning from getPage"); return rtn; }
@Override public void run() { String dateStr = new SimpleDateFormat("yyyy年MM月dd日").format(new Date()); logger.info("报工开始了,今天是:" + dateStr); isFailed = true; while (isFailed) { if (curr_try_times >= MAX_TRY_TIMES) { try { HttpClientUtils.closeQuietly(client); logger.info("连续尝试次数超过" + MAX_TRY_TIMES + "次,先休息1小时..."); Thread.sleep(1000 * 3600); curr_try_times = 0; } catch (InterruptedException e) { logger.error("线程休息出错:", e); } } curr_try_times++; start(); } }
public static void getMedia(String mediaId,File f) { LOGGER.debug("starting to get media: mediaId[{}]...", mediaId); CloseableHttpClient client = null; CloseableHttpResponse resp = null; try { client = HttpClients.createDefault(); String url = WeixinConstants.API_GET_MEDIA; url = url.replace("MEDIA_ID", mediaId); url = url.replace("ACCESS_TOKEN", AccessTokenKit.getToken()); HttpGet get = new HttpGet(url); resp = client.execute(get); int sc = resp.getStatusLine().getStatusCode(); if(sc>=200&&sc<300) { InputStream is = resp.getEntity().getContent(); FileUtils.copyInputStreamToFile(is, f); LOGGER.debug("success to get media[{}]", mediaId); } } catch (Exception e) { LOGGER.error("error get media[{}].", mediaId); } finally { HttpClientUtils.closeQuietly(resp); HttpClientUtils.closeQuietly(client); } }
public static String sendRecordingRequest(final String url) { CloseableHttpResponse response = null; try (final CloseableHttpClient client = HttpClientBuilder.create().build()) { final HttpGet get = new HttpGet(url); response = client.execute(get); HttpEntity content = response.getEntity(); String message = EntityUtils.toString(content); LOGGER.info("Response: " + message); return message; } catch (Exception ex) { LOGGER.severe("Request: " + ex); } finally { HttpClientUtils.closeQuietly(response); } return ""; }
/** * This method executes the given {@link ApacheCloudStackRequest}. * It will return the response as a plain {@link String}. * You should have in mind that if the parameter 'response' is not set, the default is 'XML'. */ public String executeRequest(ApacheCloudStackRequest request) { boolean isSecretKeyApiKeyAuthenticationMechanism = StringUtils.isNotBlank(this.apacheCloudStackUser.getApiKey()); String urlRequest = createApacheCloudStackApiUrlRequest(request, isSecretKeyApiKeyAuthenticationMechanism); LOGGER.debug(String.format("Executing request[%s].", urlRequest)); CloseableHttpClient httpClient = createHttpClient(); HttpContext httpContext = createHttpContextWithAuthenticatedSessionUsingUserCredentialsIfNeeded(httpClient, isSecretKeyApiKeyAuthenticationMechanism); try { return executeRequestGetResponseAsString(urlRequest, httpClient, httpContext); } finally { if (!isSecretKeyApiKeyAuthenticationMechanism) { executeUserLogout(httpClient, httpContext); } HttpClientUtils.closeQuietly(httpClient); } }
public FluxRuntimeConnectorHttpImpl(Long connectionTimeout, Long socketTimeout, String fluxEndpoint, ObjectMapper objectMapper) { this.fluxEndpoint = fluxEndpoint; this.objectMapper = objectMapper; RequestConfig clientConfig = RequestConfig.custom() .setConnectTimeout((connectionTimeout).intValue()) .setSocketTimeout((socketTimeout).intValue()) .setConnectionRequestTimeout((socketTimeout).intValue()) .build(); PoolingHttpClientConnectionManager syncConnectionManager = new PoolingHttpClientConnectionManager(); syncConnectionManager.setMaxTotal(MAX_TOTAL); syncConnectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE); closeableHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(clientConfig).setConnectionManager(syncConnectionManager) .build(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { HttpClientUtils.closeQuietly(closeableHttpClient); })); }
@Override public void submitNewWorkflow(StateMachineDefinition stateMachineDef) { CloseableHttpResponse httpResponse = null; try { httpResponse = postOverHttp(stateMachineDef, ""); if(logger.isDebugEnabled()) { try { logger.debug("Flux returned response: {}", EntityUtils.toString(httpResponse.getEntity())); } catch (IOException e) { e.printStackTrace(); } } } finally { HttpClientUtils.closeQuietly(httpResponse); } }
@Override public void submitEvent(String name, Object data, String correlationId, String eventSource) { final String eventType = data.getClass().getName(); if (eventSource == null) { eventSource = EXTERNAL; } CloseableHttpResponse httpResponse = null; try { final EventData eventData = new EventData(name, eventType, objectMapper.writeValueAsString(data), eventSource); httpResponse = postOverHttp(eventData, "/" + correlationId + "/context/events?searchField=correlationId"); } catch (JsonProcessingException e) { throw new RuntimeException(e); } finally { HttpClientUtils.closeQuietly(httpResponse); } }
/** Helper method to post data over Http */ private CloseableHttpResponse postOverHttp(Object dataToPost, String pathSuffix) { CloseableHttpResponse httpResponse = null; HttpPost httpPostRequest; httpPostRequest = new HttpPost(fluxEndpoint + pathSuffix); try { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); objectMapper.writeValue(byteArrayOutputStream, dataToPost); httpPostRequest.setEntity(new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ContentType.APPLICATION_JSON)); httpResponse = closeableHttpClient.execute(httpPostRequest); final int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode >= Response.Status.OK.getStatusCode() && statusCode < Response.Status.MOVED_PERMANENTLY.getStatusCode() ) { logger.trace("Posting over http is successful. Status code: {}", statusCode); } else { logger.error("Did not receive a valid response from Flux core. Status code: {}, message: {}", statusCode, EntityUtils.toString(httpResponse.getEntity())); HttpClientUtils.closeQuietly(httpResponse); throw new RuntimeCommunicationException("Did not receive a valid response from Flux core"); } } catch (IOException e) { logger.error("Posting over http errored. Message: {}", e.getMessage(), e); HttpClientUtils.closeQuietly(httpResponse); throw new RuntimeCommunicationException("Could not communicate with Flux runtime: " + fluxEndpoint); } return httpResponse; }
private HttpStreamResponse executeStream(HttpRequestBase requestBase) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, IOException { applyHeadersCommonToAllRequests(requestBase); activeCount.incrementAndGet(); CloseableHttpResponse response = client.execute(requestBase); StatusLine statusLine = response.getStatusLine(); int status = statusLine.getStatusCode(); if (status < 200 || status >= 300) { activeCount.decrementAndGet(); HttpClientUtils.closeQuietly(response); requestBase.reset(); throw new IOException("Bad status : " + statusLine); } return new HttpStreamResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase(), response, response.getEntity().getContent(), requestBase, activeCount); }
public String execute(HttpRequestBase post) throws UserErrorException { CloseableHttpClient client = null; CloseableHttpResponse resp = null; try { client = HttpClients.createDefault(); resp = client.execute(post); HttpEntity entity = resp.getEntity(); String body = EntityUtils.toString(entity); int statCode = resp.getStatusLine().getStatusCode(); if (statCode != 200) { String msg = "Expected 200 but got " + statCode; logger.warn("About to throw " + msg + " body was " + body); throw new RuntimeException(msg); } return body; } catch (Throwable e) { throw new UserErrorException("Error performing remote server post", e); } finally { HttpClientUtils.closeQuietly(resp); HttpClientUtils.closeQuietly(client); } }
protected void loadDumps() { HttpClient client = new DefaultHttpClient(); if (!downloadFolder.exists()) { downloadFolder.mkdirs(); } try { File dumpFile; for (int i = 0; i < dumps.length; ++i) { dumpFile = new File(downloadFolder.getAbsolutePath() + File.separator + extractFileName(dumps[i])); if (!dumpFile.exists()) { LOGGER.info("Start loading dump \"" + dumps[i] + "\"."); try { dumpFile = loadDump(dumps[i], dumpFile, client); } catch (Exception e) { throw new RuntimeException( "Exception while trying to download dump from \"" + dumps[i] + "\".", e); } } else { LOGGER.info(dumpFile.getAbsolutePath() + " is already existing. It won't be downloaded."); } dumps[i] = dumpFile.getAbsolutePath(); } } finally { HttpClientUtils.closeQuietly(client); } }
/** * Constructs a {@link HttpRequestResponse} from a {@link HttpResponse} by * consuming the {@link HttpResponse}'s {@link InputStream} and closing the * original {@link HttpResponse}. This constructor uses a particular * fall-back character encoding to interpret the content with should the * character encoding not be possible to determine from the response itself. * * @param httpResponse * A {@link HttpResponse} that will be consumed. That is, the * {@link HttpResponse}'s {@link InputStream} will be consumed * and closed when the method returns. * @param fallbackCharset * The character set used to interpret the message body, if the * character encoding cannot be determined from the response * itself. * @throws IOException */ public HttpRequestResponse(CloseableHttpResponse httpResponse, Charset fallbackCharset) throws IOException { try { this.statusCode = httpResponse.getStatusLine().getStatusCode(); this.headers = Arrays.asList(httpResponse.getAllHeaders()); Charset responseCharset = determineCharset(httpResponse); Charset charset = responseCharset == null ? fallbackCharset : responseCharset; // http response may not contain a message body, for example on 204 // (No Content) responses if (httpResponse.getEntity() != null) { this.responseBody = EntityUtils.toString(httpResponse.getEntity(), charset); } else { this.responseBody = null; } } finally { HttpClientUtils.closeQuietly(httpResponse); } }
protected Response executeHttpRequest(RequestBuilder httpRequest){ CloseableHttpClient client = getClient(); initHeaders(httpRequest); initParams(httpRequest); Response response = null; CloseableHttpResponse resp = null; if( entity != null ){ httpRequest.setEntity(entity); } try { final HttpUriRequest uriRequest = httpRequest.build(); resp = client.execute(uriRequest); // but make sure the response gets closed no matter what // even if do not care about its content response = new Response(resp); response.setMethod(httpRequest.getMethod()); response.setRequestLine(uriRequest.getRequestLine().toString()); } catch (Exception e) { // TODO: log the error e.printStackTrace(); } finally { HttpClientUtils.closeQuietly(client); } return response; }
public void download(String path) throws IOException { final String url = baseUrl.endsWith("/") ? baseUrl + path : baseUrl + "/" + path; final HttpGet httpGet = new HttpGet(url); final HttpResponse response = httpClient.execute(httpGet); try { if (!isSuccess(response)) { System.err.println(url); System.err.println(response.getStatusLine()); if (response.getStatusLine().getStatusCode() != 404) { throw new IOException(response.getStatusLine().toString()); } } } finally { HttpClientUtils.closeQuietly(response); } }
protected CloseableHttpResponse executeGetOrHead(HttpRequestBase method) throws IOException { final CloseableHttpResponse httpResponse = performHttpRequest(method); // Consume content for non-successful, responses. This avoids the connection being left open. if (!wasSuccessful(httpResponse)) { CloseableHttpResponse response = new AutoClosedHttpResponse(httpResponse); HttpClientUtils.closeQuietly(httpResponse); return response; } return httpResponse; }
public void upload(LocalResource resource, URI destination) throws IOException { HttpPut method = new HttpPut(destination); final RepeatableInputStreamEntity entity = new RepeatableInputStreamEntity(resource, ContentType.APPLICATION_OCTET_STREAM); method.setEntity(entity); CloseableHttpResponse response = null; try { response = http.performHttpRequest(method); if (!http.wasSuccessful(response)) { throw new IOException(String.format("Could not PUT '%s'. Received status code %s from server: %s", destination, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase())); } } finally { HttpClientUtils.closeQuietly(response); } }
@Override public boolean load(BuildCacheKey key, BuildCacheEntryReader reader) throws BuildCacheException { final URI uri = root.resolve("./" + key.getHashCode()); HttpGet httpGet = new HttpGet(uri); CloseableHttpResponse response = null; try { response = httpClient.execute(httpGet); StatusLine statusLine = response.getStatusLine(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Response for GET {}: {}", safeUri(uri), statusLine); } int statusCode = statusLine.getStatusCode(); if (statusCode >= 200 && statusCode < 300) { reader.readFrom(response.getEntity().getContent()); return true; } else if (statusCode == 404) { return false; } else { // TODO: We should consider different status codes as fatal/recoverable throw new BuildCacheException(String.format("For key '%s', using %s response status %d: %s", key, getDescription(), statusCode, statusLine.getReasonPhrase())); } } catch (IOException e) { // TODO: We should consider different types of exceptions as fatal/recoverable. // Right now, everything is considered recoverable. throw new BuildCacheException(String.format("loading key '%s' from %s", key, getDescription()), e); } finally { HttpClientUtils.closeQuietly(response); } }
public void downloadData(String symbol, long startDate, long endDate, String crumb) { String filename = String.format("%s.csv", symbol); String url = String.format("https://query1.finance.yahoo.com/v7/finance/download/%s?period1=%s&period2=%s&interval=1d&events=history&crumb=%s", symbol, startDate, endDate, crumb); HttpGet request = new HttpGet(url); System.out.println(url); request.addHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13"); try { HttpResponse response = client.execute(request, context); System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); HttpEntity entity = response.getEntity(); String reasonPhrase = response.getStatusLine().getReasonPhrase(); int statusCode = response.getStatusLine().getStatusCode(); System.out.println(String.format("statusCode: %d", statusCode)); System.out.println(String.format("reasonPhrase: %s", reasonPhrase)); if (entity != null) { BufferedInputStream bis = new BufferedInputStream(entity.getContent()); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filename))); int inByte; while((inByte = bis.read()) != -1) bos.write(inByte); bis.close(); bos.close(); } HttpClientUtils.closeQuietly(response); } catch (Exception ex) { System.out.println("Exception"); System.out.println(ex); } }
/** * 每次报工结束,关闭该client,下次报工启用新的client */ private static void getHttpClient() { HttpClientUtils.closeQuietly(client); // Locale.setDefault(new Locale("zh","CN")); HttpClientBuilder builder = HttpClientBuilder.create(); client = builder.build(); }
public static void sendGet(String url, WeixinHttpCallback c) { HttpGet get = null; CloseableHttpClient client = null; CloseableHttpResponse resp = null; try { client = HttpClients.createDefault(); url = url.replaceAll("ACCESS_TOKEN", AccessTokenKit.getToken()); LOGGER.debug("sending http get request[{}]...", url); get = new HttpGet(url); resp = client.execute(get); int statusCode = resp.getStatusLine().getStatusCode(); if(statusCode>=200 && statusCode<300) { HttpEntity entity = resp.getEntity(); String content = EntityUtils.toString(entity, Charset.forName("UTF-8")); LOGGER.debug("success to get response:[{}]", content); ErrorEntity err = JSONObject.parseObject(content, ErrorEntity.class); if(err.getErrcode()!= null || err.getErrmsg()!=null) { LOGGER.error("http[{}] response is error, errcode:[{}], errmsg:[{}].", url, err.getErrcode(), err.getErrmsg()); return; } c.process(content); LOGGER.debug("success to finish http get request."); } else { LOGGER.error("failed to get http response, http status:[{}]", statusCode); } } catch (Exception e) { LOGGER.error("failed to send http get request", e); } finally { HttpClientUtils.closeQuietly(resp); HttpClientUtils.closeQuietly(client); } }
public static void sendPost(String url, HttpEntity entity, WeixinHttpCallback c) { HttpPost post = null; CloseableHttpClient client = null; CloseableHttpResponse resp = null; try { client = HttpClients.createDefault(); url = url.replace("ACCESS_TOKEN", AccessTokenKit.getToken()); LOGGER.debug("sending http post to url:[{}]...", url); post = new HttpPost(url); post.setEntity(entity); resp = client.execute(post); int sc = resp.getStatusLine().getStatusCode(); if(sc>=200&&sc<300) { String respEntity = EntityUtils.toString(resp.getEntity(), Charset.forName("UTF-8")); LOGGER.debug("success to get response:[{}]", respEntity); if(resp.getEntity().getContentType().getValue().startsWith("application/json")) { ErrorEntity err = JSONObject.parseObject(respEntity, ErrorEntity.class); if(!"0".equals(err.getErrcode()) || !"ok".equals(err.getErrmsg())) { LOGGER.error("http[{}] response is error, errcode:[{}], errmsg:[{}].", url, err.getErrcode(), err.getErrmsg()); return; } } c.process(respEntity); LOGGER.debug("success to finish http post request."); } } catch (Exception e) { LOGGER.error("failed to send http post request", e); } finally { HttpClientUtils.closeQuietly(resp); HttpClientUtils.closeQuietly(client); } }
/** * Method Name: main<br/> * Description: [description] * @author guhanjie * @time 2016年10月11日 上午1:38:14 * @param args */ public static void main(String[] args) { HttpGet get = null; CloseableHttpClient client = null; CloseableHttpResponse resp = null; final String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=DYon2mr_xJAGKtRG-gwkh2q3PBJ3QIILlRx2XT-xZC8MmPm8bQ345aG8CttbQBD6kW1pqlKTAITpH8nFAdtvsogkdeqBwFW9rHDTcDYL3eDvALmlh5CLCRM_2TPcoLLAQFMeAEAFUB&openid=o_05Uwe4_9GGQ93ESXg27RCw6HqE&lang=zh_CN"; try { client = HttpClients.createDefault(); LOGGER.debug("sending http get request[{}]...", url); get = new HttpGet(url); resp = client.execute(get); int statusCode = resp.getStatusLine().getStatusCode(); if(statusCode>=200 && statusCode<300) { HttpEntity entity = resp.getEntity(); LOGGER.debug("content-type: [{}]", entity.getContentType().getValue()); String content = EntityUtils.toString(entity, Charset.forName("UTF-8")); LOGGER.debug("success to get response:[{}]", content); ErrorEntity err = JSONObject.parseObject(content, ErrorEntity.class); if(err.getErrcode()!= null || err.getErrmsg()!=null) { LOGGER.error("http[{}] response is error, errcode:[{}], errmsg:[{}].", url, err.getErrcode(), err.getErrmsg()); return; } LOGGER.debug("success to finish http get request."); } else { LOGGER.error("failed to get http response, http status:[{}]", statusCode); } } catch (Exception e) { LOGGER.error("failed to send http get request", e); } finally { HttpClientUtils.closeQuietly(resp); HttpClientUtils.closeQuietly(client); } }
/** * POST /repos/:owner/:repo/issues/:number/labels * ["Label1","Label2"] */ @Override public void labelPullRequest(String repoFullName, Integer issueNumber, String requestBody) { String requestUrl = new StringBuilder(githubConfig.getApiUrl()).append(repoFullName).append("/issues/").append(issueNumber).append("/labels") .append(ACCESS_TOKEN_PARAM).append(githubConfig.getAccessToken()).toString(); logger.info(requestUrl); HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead try { HttpPost request = new HttpPost(requestUrl); StringEntity params = new StringEntity(requestBody); request.addHeader("content-type", "application/x-www-form-urlencoded"); request.setEntity(params); HttpResponse response = httpClient.execute(request); logger.info("Github POST /labelPullRequest API Response status: {}", LoggingUtils.logPayload(response.getStatusLine())); // handle response here... } catch (Exception ex) { // handle exception here logger.info("Fail: Github API for Labeling PR"); } finally { HttpClientUtils.closeQuietly(httpClient); } }
public static boolean isServerStart(String url,int timeout){ long start = System.currentTimeMillis(); CloseableHttpClient client = getClient(); CloseableHttpResponse response = null; int statusCode = 0 ; try { if(timeout > 0 ){ RequestConfig config = RequestConfig.custom() .setConnectTimeout(timeout) .build(); requestConfig = config; } response = doGet(client,url); statusCode = getStatusCode(response); } catch (Exception e) { e.printStackTrace(); }finally{ HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(client); requestConfig = null; } long end = System.currentTimeMillis(); long XX = end - start; logger.info(new StringBuilder().append("[").append(url).append("]").append(" 访问时间:").append(XX).append("ms")); return statusCode == HttpStatus.SC_OK; }
@Override public void submitEventAndUpdateStatus(EventData eventData, Long stateMachineId, ExecutionUpdateData executionUpdateData) { CloseableHttpResponse httpResponse = null; try { EventAndExecutionData eventAndExecutionData = new EventAndExecutionData(eventData, executionUpdateData); httpResponse = postOverHttp(eventAndExecutionData, "/" + stateMachineId + "/context/eventandstatus"); } finally { HttpClientUtils.closeQuietly(httpResponse); } }
@Override public void cancelEvent(String eventName, String correlationId) { CloseableHttpResponse httpResponse = null; try { final EventData eventData = new EventData(eventName, null, null, null, true); httpResponse = postOverHttp(eventData, "/" + correlationId + "/context/events?searchField=correlationId"); } catch (Exception e) { throw new RuntimeException(e); } finally { HttpClientUtils.closeQuietly(httpResponse); } }
/** * Interface method implementation. Increments the execution retries in persistence by invoking suitable Flux runtime API * @see com.flipkart.flux.client.runtime.FluxRuntimeConnector#incrementExecutionRetries(java.lang.Long, java.lang.Long) */ @Override public void incrementExecutionRetries(Long stateMachineId,Long taskId) { CloseableHttpResponse httpResponse = null; httpResponse = postOverHttp(null, "/" + stateMachineId + "/" + taskId + "/retries/inc"); HttpClientUtils.closeQuietly(httpResponse); }
/** * Interface method implementation. Posts to Flux Runtime API to redrive a task. */ @Override public void redriveTask(Long taskId) { CloseableHttpResponse httpResponse = null; httpResponse = postOverHttp(null, "/redrivetask/" + taskId); HttpClientUtils.closeQuietly(httpResponse); }
private Optional<SnapshotItem> fetchLatest(ContentSpecifier spec) throws IOException { AptFacet aptFacet = getRepository().facet(AptFacet.class); ProxyFacet proxyFacet = facet(ProxyFacet.class); HttpClientFacet httpClientFacet = facet(HttpClientFacet.class); HttpClient httpClient = httpClientFacet.getHttpClient(); CacheController cacheController = cacheControllerHolder.getMetadataCacheController(); CacheInfo cacheInfo = cacheController.current(); Content oldVersion = aptFacet.get(spec.path); URI fetchUri = proxyFacet.getRemoteUrl().resolve(spec.path); HttpGet getRequest = buildFetchRequest(oldVersion, fetchUri); HttpResponse response = httpClient.execute(getRequest); StatusLine status = response.getStatusLine(); if (status.getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); Content fetchedContent = new Content(new HttpEntityPayload(response, entity)); AttributesMap contentAttrs = fetchedContent.getAttributes(); contentAttrs.set(Content.CONTENT_LAST_MODIFIED, getDateHeader(response, HttpHeaders.LAST_MODIFIED)); contentAttrs.set(Content.CONTENT_ETAG, getQuotedStringHeader(response, HttpHeaders.ETAG)); contentAttrs.set(CacheInfo.class, cacheInfo); Content storedContent = getAptFacet().put(spec.path, fetchedContent); return Optional.of(new SnapshotItem(spec, storedContent)); } try { if (status.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) { checkState(oldVersion != null, "Received 304 without conditional GET (bad server?) from %s", fetchUri); doIndicateVerified(oldVersion, cacheInfo, spec.path); return Optional.of(new SnapshotItem(spec, oldVersion)); } throwProxyExceptionForStatus(response); } finally { HttpClientUtils.closeQuietly(response); } return Optional.empty(); }
/** * Send a ping to Analytics on a separate thread */ private static void sendPing(@NotNull final List<? extends NameValuePair> postData) { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { @Override public void run() { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPost request = new HttpPost(ANALYTICS_URL); try { request.setEntity(new UrlEncodedFormEntity(postData)); HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); HttpEntity entity = response.getEntity(); // throw it away, don't care, not sure if we need to read in the response? if (status.getStatusCode() >= 300) { LOG.debug("Non 200 status code : " + status.getStatusCode() + " - " + status.getReasonPhrase()); // something went wrong, fail quietly, we probably have to diagnose analytics errors on our side // usually analytics accepts ANY request and always returns 200 } } catch (IOException e) { LOG.debug("IOException during Analytics Ping", e.getMessage()); // something went wrong, fail quietly } finally { HttpClientUtils.closeQuietly(client); } } }); }
private MessageResponse sendMessageRequest(@NonNull String pageAccessToken, @NonNull MessageRequest messageRequest) throws FacebookMessengerSendException { RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(requestTimeout) .setConnectTimeout(requestTimeout) .build(); CloseableHttpClient httpClient = HttpClients.custom() .setDefaultRequestConfig(requestConfig) .build(); CloseableHttpResponse response = null; HttpPost httpPost = null; try { httpPost = new HttpPost(facebookMessageEndPoint + pageAccessToken); httpPost.setEntity(new StringEntity(OBJECT_MAPPER.writeValueAsString(messageRequest), ContentType.APPLICATION_JSON)); response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { log.debug("Successfully sent message. messageRequest: {}", messageRequest); return OBJECT_MAPPER.readValue(response.getEntity().getContent(), MessageResponse.class); } else { log.info("Failed to send messageRequest: {} response: {}", messageRequest, response); ErrorResponse errorResponse = OBJECT_MAPPER.readValue( response.getEntity().getContent(), ErrorResponse.class); throw new FacebookMessengerSendException(errorResponse.getError()); } } catch (IOException e) { log.error("Error sending messageRequest: {}", messageRequest, e); return null; } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(httpClient); } }
/** * Helper to close HttpGet and its response * @param get Thing to be closed * @param resp Thing to be closed */ public void closeQuietly( final HttpGet get, final CloseableHttpResponse resp ) { // Response needs to be closed HttpClientUtils.closeQuietly(resp); // Closing the request is not an absolute requirement if (get != null) get.releaseConnection(); }
/** * Helper to close HttpPost and its response * @param post Thing to be closed * @param resp Thing to be closed */ public void closeQuietly( final HttpPost post, final CloseableHttpResponse resp ) { // Response needs to be closed HttpClientUtils.closeQuietly(resp); // Closing the request is not an absolute requirement if (post != null) post.releaseConnection(); }
/** * 调用融宝快捷支付接口 * @param reapal_url * @param paramMap * @return */ public static String reapalPost(String reapal_url, Map<String, String> paramMap){ logger.debug("URL:{}请求{}",reapal_url,paramMap); String response = null; CloseableHttpClient httpclient = null; CloseableHttpResponse chResp = null; try{ ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); for(String key:paramMap.keySet()){ postParameters.add(new BasicNameValuePair(key, paramMap.get(key))); } URL url = new URL(reapal_url); httpclient = newInstance(); HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); HttpPost httppost = new HttpPost(reapal_url); // httppost.addHeader("Content-Type", "text/html;charset=UTF-8"); //httppost.setEntity(new UrlEncodedFormEntity(postParameters,"UTF-8")); httppost.setEntity(new UrlEncodedFormEntity(postParameters)); chResp = httpclient.execute(targetHost, httppost, context); logger.debug("executing request" + httppost.getRequestLine()); HttpEntity entity = chResp.getEntity(); logger.debug(chResp.getStatusLine().toString()); if(entity==null){ logger.error("reapal response is null."); return null; }else{ response = EntityUtils.toString(entity); } }catch(Exception e){ logger.error("融宝支付POST异常:{}",e); }finally{ //关闭输出流 HttpClientUtils.closeQuietly(chResp); // HttpClientUtils.closeQuietly(httpclient); } return response; }
@Override public void close() { try { HttpClientUtils.closeQuietly(client); onClose.close(); } catch (IOException t) { LOG.error("Failed to close client", t); } }
private byte[] getResrponseEntityBytes(URI uriForFavoritesBuilds) { HttpGet httpGet = new HttpGet(uriForFavoritesBuilds); CloseableHttpResponse httpResponse = null; byte[] entityBytes; try { httpResponse = httpClient.execute(httpGet); validateResponse(httpResponse); entityBytes = EntityUtils.toByteArray(httpResponse.getEntity()); } catch (Exception e) { throw new RuntimeException("Failed obtaining of favourite builds from '" + uriForFavoritesBuilds + "'", e); } finally { HttpClientUtils.closeQuietly(httpResponse); } return entityBytes; }
@SuppressWarnings("FutureReturnValueIgnored") private void sendPing(@NotNull final List<? extends NameValuePair> postData) { ApplicationManager.getApplication() .executeOnPooledThread( () -> { CloseableHttpClient client = HttpClientBuilder.create().setUserAgent(userAgent).build(); HttpPost request = new HttpPost(ANALYTICS_URL); try { request.setEntity(new UrlEncodedFormEntity(postData)); CloseableHttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() >= 300) { logger.debug( "Non 200 status code : " + status.getStatusCode() + " - " + status.getReasonPhrase()); } } catch (IOException ex) { logger.debug("IOException during Analytics Ping", ex.getMessage()); } finally { HttpClientUtils.closeQuietly(client); } }); }