本文整理了Java中org.eclipse.jetty.client.HttpClient
类的一些代码示例,展示了HttpClient
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpClient
类的具体详情如下:
包路径:org.eclipse.jetty.client.HttpClient
类名称:HttpClient
[英]Http Client.
HttpClient is the main active component of the client API implementation. It is the opposite of the Connectors in standard Jetty, in that it listens for responses rather than requests. Just like the connectors, there is a blocking socket version and a non-blocking NIO version (implemented as nested classes selected by #setConnectorType(int)).
The an instance of HttpExchange is passed to the #send(HttpExchange) method to send a request. The exchange contains both the headers and content (source) of the request plus the callbacks to handle responses. A HttpClient can have many exchanges outstanding and they may be queued on the HttpDestination waiting for a AbstractHttpConnection, queued in the AbstractHttpConnection waiting to be transmitted or pipelined on the actual TCP/IP connection waiting for a response.
The HttpDestination class is an aggregation of AbstractHttpConnections for the same host, port and protocol. A destination may limit the number of connections open and they provide a pool of open connections that may be reused. Connections may also be allocated from a destination, so that multiple request sources are not multiplexed over the same connection.
[中]Http客户端。
HttpClient是客户端API实现的主要活动组件。它与标准Jetty中的连接器相反,因为它侦听响应而不是请求。与连接器一样,有一个阻塞套接字版本和一个非阻塞NIO版本(实现为由#setConnectorType(int)选择的嵌套类)。
HttpExchange的an实例被传递到#send(HttpExchange)方法以发送请求。交换包含请求的头和内容(源)以及处理响应的回调。HttpClient可以有许多未完成的交换,它们可能在HttpDestination上排队等待AbstractHttpConnection,在AbstractHttpConnection中排队等待传输,或者在实际TCP/IP连接上排队等待响应。
HttpDestination类是同一主机、端口和协议的抽象HttpConnections的聚合。目标可能会限制打开的连接数,并提供可重用的打开连接池。还可以从目的地分配连接,以便在同一连接上不复用多个请求源。
代码示例来源:origin: xuxueli/xxl-job
httpClient = new HttpClient();
httpClient.setFollowRedirects(false); // Configure HttpClient, for example:
httpClient.start(); // Start HttpClient
Request request = httpClient.newRequest(param);
request.method(HttpMethod.GET);
request.timeout(5000, TimeUnit.MILLISECONDS);
ContentResponse response = request.send();
if (response.getStatus() != HttpStatus.OK_200) {
XxlJobLogger.log("Http StatusCode({}) Invalid.", response.getStatus());
} finally {
if (httpClient != null) {
httpClient.stop();
代码示例来源:origin: databricks/learning-spark
public Iterable<String> call(Iterator<String> input) {
ArrayList<String> content = new ArrayList<String>();
ArrayList<ContentExchange> cea = new ArrayList<ContentExchange>();
HttpClient client = new HttpClient();
try {
client.start();
while (input.hasNext()) {
ContentExchange exchange = new ContentExchange(true);
exchange.setURL("http://qrzcq.com/call/" + input.next());
client.send(exchange);
cea.add(exchange);
}
for (ContentExchange exchange : cea) {
exchange.waitForDone();
content.add(exchange.getResponseContent());
}
} catch (Exception e) {
}
return content;
}});
System.out.println(StringUtils.join(result.collect(), ","));
代码示例来源:origin: jersey/jersey
sslContextFactory.setEndpointIdentificationAlgorithm("https");
this.client = new HttpClient(sslContextFactory);
client.setConnectTimeout((Integer) connectTimeout);
final QueuedThreadPool threadPool = new QueuedThreadPool((Integer) threadPoolSize);
threadPool.setName(name);
client.setExecutor(threadPool);
final AuthenticationStore auth = client.getAuthenticationStore();
final Object basicAuthProvider = config.getProperty(JettyClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION);
if (basicAuthProvider != null && (basicAuthProvider instanceof BasicAuthentication)) {
if (proxyUri != null) {
final URI u = getProxyUri(proxyUri);
final ProxyConfiguration proxyConfig = client.getProxyConfiguration();
proxyConfig.getProxies().add(new HttpProxy(u.getHost(), u.getPort()));
client.setCookieStore(new HttpCookieStore.Empty());
client.start();
} catch (final Exception e) {
throw new ProcessingException("Failed to start the client.", e);
this.cookieStore = client.getCookieStore();
代码示例来源:origin: spring-projects/spring-framework
@Override
public void start() {
try {
if (!this.httpClient.isRunning()) {
this.httpClient.start();
}
}
catch (Exception ex) {
throw new SockJsException("Failed to start JettyXhrTransport", ex);
}
}
代码示例来源:origin: spring-projects/spring-framework
@Override
public void stop() {
try {
if (this.httpClient.isRunning()) {
this.httpClient.stop();
}
}
catch (Exception ex) {
throw new SockJsException("Failed to stop JettyXhrTransport", ex);
}
}
代码示例来源:origin: spring-projects/spring-framework
/**
* Constructor with an {@link JettyResourceFactory} that will manage shared resources.
* @param resourceFactory the {@link JettyResourceFactory} to use
* @param customizer the lambda used to customize the {@link HttpClient}
*/
public JettyClientHttpConnector(
JettyResourceFactory resourceFactory, @Nullable Consumer<HttpClient> customizer) {
HttpClient httpClient = new HttpClient();
httpClient.setExecutor(resourceFactory.getExecutor());
httpClient.setByteBufferPool(resourceFactory.getByteBufferPool());
httpClient.setScheduler(resourceFactory.getScheduler());
if (customizer != null) {
customizer.accept(httpClient);
}
this.httpClient = httpClient;
}
代码示例来源:origin: spring-projects/spring-framework
protected ResponseEntity<String> executeRequest(URI url, HttpMethod method,
HttpHeaders headers, @Nullable String body) {
Request httpRequest = this.httpClient.newRequest(url).method(method);
addHttpHeaders(httpRequest, headers);
if (body != null) {
httpRequest.content(new StringContentProvider(body));
}
ContentResponse response;
try {
response = httpRequest.send();
}
catch (Exception ex) {
throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
}
HttpStatus status = HttpStatus.valueOf(response.getStatus());
HttpHeaders responseHeaders = toHttpHeaders(response.getHeaders());
return (response.getContent() != null ?
new ResponseEntity<>(response.getContentAsString(), responseHeaders, status) :
new ResponseEntity<>(responseHeaders, status));
}
代码示例来源:origin: org.infinispan/infinispan-server-rest
@Test
public void shouldHandleIncompletePath() throws Exception {
Request req = client.newRequest(String.format("http://localhost:%d/rest/%s?action", restServer().getPort(), "default"))
.method(HttpMethod.GET);
ContentResponse response = req.send();
ResponseAssertion.assertThat(response).isBadRequest();
}
代码示例来源:origin: com.teradata.airlift/http-server
private static HttpClient createClientIncludeCiphers(String... includedCipherSuites)
throws Exception
{
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setIncludeCipherSuites(includedCipherSuites);
sslContextFactory.setKeyStorePath(KEY_STORE_PATH);
sslContextFactory.setKeyStorePassword(KEY_STORE_PASSWORD);
HttpClient httpClient = new HttpClient(sslContextFactory);
httpClient.start();
return httpClient;
}
代码示例来源:origin: io.leopard/leopard-jetty
@Override
protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
final int requestId = getRequestId(request);
String rewrittenTarget = rewriteTarget(request);
if (_log.isDebugEnabled()) {
StringBuffer uri = request.getRequestURL();
if (request.getQueryString() != null)
uri.append("?").append(request.getQueryString());
if (_log.isDebugEnabled())
_log.debug("{} rewriting: {} -> {}", requestId, uri, rewrittenTarget);
}
if (rewrittenTarget == null) {
onProxyRewriteFailed(request, response);
return;
}
final Request proxyRequest = getHttpClient().newRequest(rewrittenTarget).method(request.getMethod()).version(HttpVersion.fromString(request.getProtocol()));
copyRequestHeaders(request, proxyRequest);
addProxyHeaders(request, proxyRequest);
// final AsyncContext asyncContext = request.startAsync();
// We do not timeout the continuation, but the proxy request
// asyncContext.setTimeout(0);
proxyRequest.timeout(getTimeout(), TimeUnit.MILLISECONDS);
if (hasContent(request))
proxyRequest.content(proxyRequestContent(request, response, proxyRequest));
sendProxyRequest(request, response, proxyRequest);
}
代码示例来源:origin: stackoverflow.com
// Setup and start HttpClient with HTTP/2 transport.
HTTP2Client http2Client = new HTTP2Client();
SslContextFactory sslContextFactory = new SslContextFactory();
HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client), sslContextFactory);
httpClient.start();
// Make a request.
ContentResponse response = httpClient.GET("https://webtide.com/");
代码示例来源:origin: sixt/ja-micro
private HttpClient createHttpClient() {
//Allow ssl by default
SslContextFactory sslContextFactory = new SslContextFactory();
//Don't exclude RSA because Sixt needs them, dammit!
sslContextFactory.setExcludeCipherSuites("");
HttpClient client = new HttpClient(sslContextFactory);
client.setFollowRedirects(false);
client.setMaxConnectionsPerDestination(16);
client.setRequestBufferSize(65536);
client.setConnectTimeout(FeatureFlags.getHttpConnectTimeout(serviceProperties));
client.setAddressResolutionTimeout(FeatureFlags.getHttpAddressResolutionTimeout(serviceProperties));
//You can set more restrictive timeouts per request, but not less, so
// we set the maximum timeout of 1 hour here.
client.setIdleTimeout(60 * 60 * 1000);
try {
client.start();
} catch (Exception e) {
logger.error("Error building http client", e);
}
return client;
}
代码示例来源:origin: sixt/ja-micro
private HttpClient createHttpClient() {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setExcludeCipherSuites("");
HttpClient client = new HttpClient(sslContextFactory);
client.setFollowRedirects(false);
client.setMaxConnectionsPerDestination(2);
//You can set more restrictive timeouts per request, but not less, so
// we set the maximum timeout of 1 hour here.
client.setIdleTimeout(60 * 60 * 1000);
try {
client.start();
} catch (Exception e) {
logger.error("Error building http client", e);
}
return client;
}
代码示例来源:origin: apache/incubator-druid
final SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setSslContext(getSslContextBinding().getProvider().get());
httpClient = new HttpClient(sslContextFactory);
} else {
httpClient = new HttpClient();
httpClient.setIdleTimeout(config.getReadTimeout().getMillis());
httpClient.setMaxConnectionsPerDestination(config.getNumConnections());
httpClient.setMaxRequestsQueuedPerDestination(config.getNumRequestsQueued());
httpClient.setConnectTimeout(CLIENT_CONNECT_TIMEOUT_MILLIS);
httpClient.setRequestBufferSize(config.getRequestBuffersize());
final QueuedThreadPool pool = new QueuedThreadPool(config.getNumMaxThreads());
pool.setName(JettyHttpClientModule.class.getSimpleName() + "-threadPool-" + pool.hashCode());
httpClient.setExecutor(pool);
代码示例来源:origin: labsai/EDDI
@Provides
@Singleton
public HttpClient provideHttpClient(ExecutorService executorService,
@Named("httpClient.maxConnectionsQueued") Integer maxConnectionsQueued,
@Named("httpClient.maxConnectionPerRoute") Integer maxConnectionPerRoute,
@Named("httpClient.requestBufferSize") Integer requestBufferSize,
@Named("httpClient.responseBufferSize") Integer responseBufferSize,
@Named("httpClient.maxRedirects") Integer maxRedirects,
@Named("httpClient.trustAllCertificates") Boolean trustAllCertificates) {
try {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setTrustAll(trustAllCertificates);
HttpClient httpClient = new HttpClient(sslContextFactory);
httpClient.setExecutor(executorService);
httpClient.setMaxConnectionsPerDestination(maxConnectionsQueued);
httpClient.setMaxRequestsQueuedPerDestination(maxConnectionPerRoute);
httpClient.setRequestBufferSize(requestBufferSize);
httpClient.setResponseBufferSize(responseBufferSize);
httpClient.setMaxRedirects(maxRedirects);
httpClient.start();
registerHttpClientShutdownHook(httpClient);
return httpClient;
} catch (Exception e) {
System.out.println(Arrays.toString(e.getStackTrace()));
throw new RuntimeException(e.getLocalizedMessage(), e);
}
}
代码示例来源:origin: RusticiSoftware/TinCanJava
private static HttpClient httpClient() throws Exception {
if (_httpClient == null ) {
_httpClient = new HttpClient(new SslContextFactory());
_httpClient.setConnectTimeout(TIMEOUT_CONNECT);
_httpClient.setFollowRedirects(false);
_httpClient.setCookieStore(new HttpCookieStore.Empty());
_httpClient.start();
_ourClient = true;
}
return _httpClient;
}
代码示例来源:origin: org.eclipse.smarthome.ui/org.eclipse.smarthome.ui
/**
* Override <code>newHttpClient</code> so we can proxy to HTTPS URIs.
*/
@Override
protected HttpClient newHttpClient() {
return new HttpClient(new SslContextFactory());
}
代码示例来源:origin: stackoverflow.com
/*配置sslcontextfactory处理https请求*/
SslContextFactory sslContextFactory = new SslContextFactory();
HttpClient httpClient = new HttpClient(sslContextFactory);
httpClient.setFollowRedirects(false);
httpClient.start();
/*配置post请求的url、body、以及请求头*/
Request request = httpClient.POST("https://a1.easemob.com/yinshenxia/yinshenxia/users");
request.header(HttpHeader.CONTENT_TYPE, "application/json");
request.content(new StringContentProvider("{\"username\":\"jliu\",\"password\":\"123456\"}","utf-8"));
// request.param("username", "jliu");
// request.param("password", "123456");
ContentResponse response = request.send();
String res = new String(response.getContent());
System.out.println(res);
httpClient.stop();
代码示例来源:origin: org.apache.cayenne/cayenne-client-jetty
protected HttpClient initJettyHttpClient() {
try {
HttpClient httpClient = new HttpClient(new SslContextFactory());
httpClient.start();
return httpClient;
} catch (Exception e) {
throw new CayenneRuntimeException("Exception while starting Jetty HttpClient.", e);
}
}
代码示例来源:origin: org.eclipse.jetty.aggregate/jetty-all-server
final int debug = _log.isDebugEnabled()?request.hashCode():0;
_log.debug("{} {} {} {}", debug ,request.getMethod(), url, request.getProtocol());
long ctimeout = (_client.getTimeout() > exchange.getTimeout())?_client.getTimeout():exchange.getTimeout();
exchange.setTimeout(ctimeout);
_client.send(exchange);
_log.info("Exception while waiting for response on proxied request", e);
内容来源于网络,如有侵权,请联系作者删除!