當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpClientUtils類代碼示例

本文整理匯總了Java中org.apache.http.client.utils.HttpClientUtils的典型用法代碼示例。如果您正苦於以下問題:Java HttpClientUtils類的具體用法?Java HttpClientUtils怎麽用?Java HttpClientUtils使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


HttpClientUtils類屬於org.apache.http.client.utils包,在下文中一共展示了HttpClientUtils類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getPage

import org.apache.http.client.utils.HttpClientUtils; //導入依賴的package包/類
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;
}
 
開發者ID:bradlucas,項目名稱:get-yahoo-quotes-java,代碼行數:27,代碼來源:GetYahooQuotes.java

示例2: run

import org.apache.http.client.utils.HttpClientUtils; //導入依賴的package包/類
@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();
	}
}
 
開發者ID:ichatter,項目名稱:dcits-report,代碼行數:22,代碼來源:Start.java

示例3: getMedia

import org.apache.http.client.utils.HttpClientUtils; //導入依賴的package包/類
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);
    }
}
 
開發者ID:guhanjie,項目名稱:weixin-boot,代碼行數:25,代碼來源:MediaKit.java

示例4: sendRecordingRequest

import org.apache.http.client.utils.HttpClientUtils; //導入依賴的package包/類
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 "";
}
 
開發者ID:SergeyPirogov,項目名稱:video-recorder-java,代碼行數:17,代碼來源:RestUtils.java

示例5: executeRequest

import org.apache.http.client.utils.HttpClientUtils; //導入依賴的package包/類
/**
 * 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);
    }
}
 
開發者ID:Autonomiccs,項目名稱:apache-cloudstack-java-client,代碼行數:21,代碼來源:ApacheCloudStackClient.java

示例6: FluxRuntimeConnectorHttpImpl

import org.apache.http.client.utils.HttpClientUtils; //導入依賴的package包/類
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);
    }));
}
 
開發者ID:flipkart-incubator,項目名稱:flux,代碼行數:20,代碼來源:FluxRuntimeConnectorHttpImpl.java

示例7: submitNewWorkflow

import org.apache.http.client.utils.HttpClientUtils; //導入依賴的package包/類
@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);
    }
}
 
開發者ID:flipkart-incubator,項目名稱:flux,代碼行數:17,代碼來源:FluxRuntimeConnectorHttpImpl.java

示例8: submitEvent

import org.apache.http.client.utils.HttpClientUtils; //導入依賴的package包/類
@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);
    }
}
 
開發者ID:flipkart-incubator,項目名稱:flux,代碼行數:17,代碼來源:FluxRuntimeConnectorHttpImpl.java

示例9: postOverHttp

import org.apache.http.client.utils.HttpClientUtils; //導入依賴的package包/類
/** 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;
}
 
開發者ID:flipkart-incubator,項目名稱:flux,代碼行數:26,代碼來源:FluxRuntimeConnectorHttpImpl.java

示例10: executeStream

import org.apache.http.client.utils.HttpClientUtils; //導入依賴的package包/類
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);
}
 
開發者ID:jivesoftware,項目名稱:routing-bird,代碼行數:25,代碼來源:ApacheHttpClient441BackedHttpClient.java

示例11: execute

import org.apache.http.client.utils.HttpClientUtils; //導入依賴的package包/類
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);
    }
}
 
開發者ID:memphis-iis,項目名稱:gluten,代碼行數:27,代碼來源:HttpClient.java

示例12: loadDumps

import org.apache.http.client.utils.HttpClientUtils; //導入依賴的package包/類
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);
	}
}
 
開發者ID:dice-group,項目名稱:Tapioca,代碼行數:27,代碼來源:DumpLoadingTask.java

示例13: HttpRequestResponse

import org.apache.http.client.utils.HttpClientUtils; //導入依賴的package包/類
/**
 * 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);
    }
}
 
開發者ID:elastisys,項目名稱:scale.commons,代碼行數:36,代碼來源:HttpRequestResponse.java

示例14: executeHttpRequest

import org.apache.http.client.utils.HttpClientUtils; //導入依賴的package包/類
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;
}
 
開發者ID:datoin,項目名稱:http-requests,代碼行數:27,代碼來源:Request.java

示例15: download

import org.apache.http.client.utils.HttpClientUtils; //導入依賴的package包/類
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);
  }
}
 
開發者ID:sonatype,項目名稱:nexus-perf,代碼行數:20,代碼來源:NugetDownloadAction.java


注:本文中的org.apache.http.client.utils.HttpClientUtils類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。