本文整理汇总了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;
}
示例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();
}
}
示例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);
}
}
示例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 "";
}
示例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);
}
}
示例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);
}));
}
示例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);
}
}
示例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);
}
}
示例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;
}
示例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);
}
示例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);
}
}
示例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);
}
}
示例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);
}
}
示例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;
}
示例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);
}
}