本文整理了Java中org.apache.commons.httpclient.HttpClient
类的一些代码示例,展示了HttpClient
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpClient
类的具体详情如下:
包路径:org.apache.commons.httpclient.HttpClient
类名称:HttpClient
[英]An HTTP "user-agent", containing an HttpState and one or more HttpConnection, to which HttpMethod can be applied.
[中]HTTP“用户代理”,包含一个HttpState和一个或多个HttpConnection,HttpMethod可应用于该连接。
代码示例来源:origin: apache/incubator-pinot
URL url = new URL("http", host, port, "/schemas/" + schemaName);
GetMethod httpGet = new GetMethod(url.toString());
try {
int responseCode = HTTP_CLIENT.executeMethod(httpGet);
String response = httpGet.getResponseBodyAsString();
if (responseCode >= 400) {
httpGet.releaseConnection();
代码示例来源:origin: jenkinsci/jenkins
URL url = new URL(testUrl);
host = url.getHost();
} catch (MalformedURLException e) {
return FormValidation.error(Messages.ProxyConfiguration_MalformedTestUrl(testUrl));
method = new GetMethod(testUrl);
method.getParams().setParameter("http.socket.timeout", DEFAULT_CONNECT_TIMEOUT_MILLIS > 0 ? DEFAULT_CONNECT_TIMEOUT_MILLIS : new Integer(30 * 1000));
HttpClient client = new HttpClient();
if (Util.fixEmptyAndTrim(name) != null && !isNoProxyHost(host, noProxyHost)) {
client.getHostConfiguration().setProxy(name, port);
Credentials credentials = createCredentials(userName, password);
AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
client.getState().setProxyCredentials(scope, credentials);
int code = client.executeMethod(method);
if (code != HttpURLConnection.HTTP_OK) {
return FormValidation.error(Messages.ProxyConfiguration_FailedToConnect(testUrl, code));
} finally {
if (method != null) {
method.releaseConnection();
代码示例来源:origin: openhab/openhab1-addons
String proxyPassword, String nonProxyHosts) {
HttpClient client = new HttpClient();
client.getHostConfiguration().setProxy(proxyHost, proxyPort);
if (StringUtils.isNotBlank(proxyUser)) {
client.getState().setProxyCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(proxyUser, proxyPassword));
method.getParams().setSoTimeout(timeout);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
if (httpHeaders != null) {
for (String httpHeaderKey : httpHeaders.stringPropertyNames()) {
method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey)));
client.getParams().setAuthenticationPreemptive(true);
client.getState().setCredentials(AuthScope.ANY, credentials);
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
logger.debug("Method failed: {}", method.getStatusLine());
代码示例来源:origin: elastic/elasticsearch-hadoop
private void completeAuth(Object[] authSettings) {
if (authSettings[1] != null) {
client.setState((HttpState) authSettings[1]);
client.getParams().setAuthenticationPreemptive(true);
}
}
代码示例来源:origin: apache/incubator-gobblin
@Override
public HttpClient create() throws Exception {
HttpClient client = new HttpClient();
if (soTimeout >= 0) {
client.getParams().setSoTimeout(soTimeout);
}
if (connTimeout >= 0) {
client.getHttpConnectionManager().getParams().setConnectionTimeout(connTimeout);
}
return client;
}
代码示例来源:origin: apache/incubator-pinot
/**
* GET urls in parallel using the executor service.
* @param urls absolute URLs to GET
* @param timeoutMs timeout in milliseconds for each GET request
* @return instance of CompletionService. Completion service will provide
* results as they arrive. The order is NOT same as the order of URLs
*/
public CompletionService<GetMethod> execute(List<String> urls, int timeoutMs) {
HttpClientParams clientParams = new HttpClientParams();
clientParams.setConnectionManagerTimeout(timeoutMs);
HttpClient client = new HttpClient(clientParams, _connectionManager);
CompletionService<GetMethod> completionService = new ExecutorCompletionService<>(_executor);
for (String url : urls) {
completionService.submit(() -> {
try {
GetMethod getMethod = new GetMethod(url);
getMethod.getParams().setSoTimeout(timeoutMs);
client.executeMethod(getMethod);
return getMethod;
} catch (Exception e) {
// Log only exception type and message instead of the whole stack trace
LOGGER.warn("Caught '{}' while executing GET on URL: {}", e.toString(), url);
throw e;
}
});
}
return completionService;
}
}
代码示例来源:origin: weld/core
@Test
public void testSessionListenerInjection(@ArquillianResource URL baseURL) throws Exception {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(new URL(baseURL, "bat?mode=session").toExternalForm());
int sc = client.executeMethod(method);
assertEquals(HttpServletResponse.SC_OK, sc);
}
}
代码示例来源:origin: apache/incubator-pinot
URL url = new URL("http", host, port, "/schemas");
PostMethod httpPost = new PostMethod(url.toString());
try {
Part[] parts = {new StringPart(schema.getSchemaName(), schema.toString())};
MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts, new HttpMethodParams());
httpPost.setRequestEntity(requestEntity);
int responseCode = HTTP_CLIENT.executeMethod(httpPost);
if (responseCode >= 400) {
String response = httpPost.getResponseBodyAsString();
LOGGER.warn("Got error response code: {}, response: {}", responseCode, response);
return false;
代码示例来源:origin: apache/incubator-pinot
/**
* Given host, port and schema name, send a http DELETE request to delete the {@link Schema}.
*
* @return <code>true</code> on success.
* <P><code>false</code> on failure.
*/
public static boolean deleteSchema(@Nonnull String host, int port, @Nonnull String schemaName) {
Preconditions.checkNotNull(host);
Preconditions.checkNotNull(schemaName);
try {
URL url = new URL("http", host, port, "/schemas/" + schemaName);
DeleteMethod httpDelete = new DeleteMethod(url.toString());
try {
int responseCode = HTTP_CLIENT.executeMethod(httpDelete);
if (responseCode >= 400) {
String response = httpDelete.getResponseBodyAsString();
LOGGER.warn("Got error response code: {}, response: {}", responseCode, response);
return false;
}
return true;
} finally {
httpDelete.releaseConnection();
}
} catch (Exception e) {
LOGGER.error("Caught exception while getting the schema: {} from host: {}, port: {}", schemaName, host, port, e);
return false;
}
}
代码示例来源:origin: it.geosolutions/geonetwork-manager
private static void setAuth(HttpClient client, String url, String username, String pw) throws MalformedURLException {
URL u = new URL(url);
if(username != null && pw != null) {
Credentials defaultcreds = new UsernamePasswordCredentials(username, pw);
client.getState().setCredentials(new AuthScope(u.getHost(), u.getPort()), defaultcreds);
client.getParams().setAuthenticationPreemptive(true); // GS2 by default always requires authentication
} else {
if(LOGGER.isTraceEnabled()) {
LOGGER.trace("Not setting credentials to access to " + url);
}
}
}
代码示例来源:origin: org.n52.security/52n-security-facade
private static InputStream requestDoc(URL url) throws IOException {
HttpClient client = new HttpClient();
ProxyManager proxyManager = new ProxyManager();
ProxyHost proxy = proxyManager.getProxyHost(url);
if (proxy != null) {
LOG.debug("for server " + url + " using proxy: '" + proxy.getHostName() + "'");
} else {
LOG.debug("for server " + url + " not using proxy!");
}
client.getHostConfiguration().setProxyHost(proxy);
client.getState().setProxyCredentials(AuthScope.ANY, proxyManager.getProxyCredentials(url));
GetMethod method = new GetMethod(url.toString());
client.executeMethod(method);
return method.getResponseBodyAsStream();
}
代码示例来源:origin: org.n52.security/52n-security-facade
private PAOSResponse requestPAOSResponse() throws ServiceException {
GetMethod method = new GetMethod(getURL().toString());
method.addRequestHeader(new Header("Accept", "application/vnd.paos+xml"));
method.addRequestHeader(new Header("PAOS",
"ver='urn:liberty:paos:2003-08';'urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp'"));
try {
m_client.executeMethod(method);
InputStream responseBodyStream = method.getResponseBodyAsStream();
PAOSResponse paosResponse = PAOSResponse.createFromXMLStream(responseBodyStream);
return paosResponse;
} catch (Exception e) {
throw new ServiceException(String.format("Could not send basic GET request to <%s>.", getURL()),
ServiceException.SERVICE_ERROR, e);
} finally {
method.releaseConnection();
}
}
代码示例来源:origin: geotools/geotools
@Override
public HTTPResponse get(final URL url) throws IOException {
GetMethod getMethod = new GetMethod(url.toExternalForm());
getMethod.setDoAuthentication(user != null && password != null);
int responseCode = client.executeMethod(getMethod);
if (200 != responseCode) {
getMethod.releaseConnection();
throw new IOException(
"Server returned HTTP error code "
+ responseCode
+ " for URL "
+ url.toExternalForm());
}
return new HttpMethodResponse(getMethod);
}
代码示例来源:origin: geotools/geotools
private InputStream setupInputStream(URL url, Map<String, String> headers) throws IOException {
HttpClient client = new HttpClient();
String uri = url.toExternalForm();
if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, "URL is " + uri);
HttpMethod get = new GetMethod(uri);
if (MapUtils.isNotEmpty(headers)) {
for (String headerName : headers.keySet()) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(
Level.FINE,
"Adding header " + headerName + " = " + headers.get(headerName));
}
get.addRequestHeader(headerName, headers.get(headerName));
}
}
int code = client.executeMethod(get);
if (code != 200) {
throw new IOException("Connection returned code " + code);
}
return get.getResponseBodyAsStream();
}
}
代码示例来源:origin: geotools/geotools
@Override
public HTTPResponse post(
final URL url, final InputStream postContent, final String postContentType)
throws IOException {
PostMethod postMethod = new PostMethod(url.toExternalForm());
postMethod.setDoAuthentication(user != null && password != null);
if (postContentType != null) {
postMethod.setRequestHeader("Content-type", postContentType);
}
RequestEntity requestEntity = new InputStreamRequestEntity(postContent);
postMethod.setRequestEntity(requestEntity);
int responseCode = client.executeMethod(postMethod);
if (200 != responseCode) {
postMethod.releaseConnection();
throw new IOException(
"Server returned HTTP error code "
+ responseCode
+ " for URL "
+ url.toExternalForm());
}
return new HttpMethodResponse(postMethod);
}
代码示例来源:origin: KylinOLAP/Kylin
private void init(String host, int port, String userName, String password) {
this.host = host;
this.port = port;
this.userName = userName;
this.password = password;
this.baseUrl = "http://" + host + ":" + port + "/kylin/api";
client = new HttpClient();
if (userName != null && password != null) {
client.getParams().setAuthenticationPreemptive(true);
Credentials creds = new UsernamePasswordCredentials(userName, password);
client.getState().setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), creds);
}
}
代码示例来源:origin: apache/cloudstack
try {
String url = buildUrl(buildParams(command, params), region);
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
if (client.executeMethod(method) == 200) {
InputStream is = method.getResponseBodyAsStream();
XStream xstream = new XStream(new DomDriver());
xstream.alias("useraccount", UserAccountVO.class);
代码示例来源:origin: apache/cloudstack
public static InputStream getInputStreamFromUrl(String url, String user, String password) {
try {
Pair<String, Integer> hostAndPort = validateUrl(url);
HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager());
if ((user != null) && (password != null)) {
httpclient.getParams().setAuthenticationPreemptive(true);
Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
httpclient.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
}
// Execute the method.
GetMethod method = new GetMethod(url);
int statusCode = httpclient.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
s_logger.error("Failed to read from URL: " + url);
return null;
}
return method.getResponseBodyAsStream();
} catch (Exception ex) {
s_logger.error("Failed to read from URL: " + url);
return null;
}
}
代码示例来源:origin: com.facebook.hadoop/hadoop-core
private static int httpNotification(String uri) throws IOException {
URI url = new URI(uri, false);
HttpClient m_client = new HttpClient();
HttpMethod method = new GetMethod(url.getEscapedURI());
method.setRequestHeader("Accept", "*/*");
return m_client.executeMethod(method);
}
代码示例来源:origin: apache/incubator-gobblin
GetMethod get = new GetMethod(schemaUrl);
HttpClient httpClient = this.borrowClient();
try {
statusCode = httpClient.executeMethod(get);
schemaString = get.getResponseBodyAsString();
} catch (HttpException e) {
throw new RuntimeException(e);
throw new RuntimeException(e);
} finally {
get.releaseConnection();
this.httpClientPool.returnObject(httpClient);
内容来源于网络,如有侵权,请联系作者删除!