org.apache.commons.httpclient.HttpClient.<init>()方法的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(11.3k)|赞(0)|评价(0)|浏览(177)

本文整理了Java中org.apache.commons.httpclient.HttpClient.<init>()方法的一些代码示例,展示了HttpClient.<init>()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpClient.<init>()方法的具体详情如下:
包路径:org.apache.commons.httpclient.HttpClient
类名称:HttpClient
方法名:<init>

HttpClient.<init>介绍

[英]Creates an instance of HttpClient using default HttpClientParams.
[中]使用默认的HttpClientParams创建HttpClient实例。

代码示例

代码示例来源:origin: apache/incubator-pinot

@Override
public boolean execute()
  throws Exception {
 if (_controllerHost == null) {
  _controllerHost = NetUtil.getHostAddress();
 }
 String stateValue = _state.toLowerCase();
 if (!stateValue.equals("enable") && !stateValue.equals("disable") && !stateValue.equals("drop")) {
  throw new IllegalArgumentException(
    "Invalid value for state: " + _state + "\n Value must be one of enable|disable|drop");
 }
 HttpClient httpClient = new HttpClient();
 HttpURL url = new HttpURL(_controllerHost, Integer.parseInt(_controllerPort), URI_TABLES_PATH + _tableName);
 url.setQuery("state", stateValue);
 GetMethod httpGet = new GetMethod(url.getEscapedURI());
 int status = httpClient.executeMethod(httpGet);
 if (status != 200) {
  throw new RuntimeException("Failed to change table state, error: " + httpGet.getResponseBodyAsString());
 }
 return true;
}

代码示例来源: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: ysc/QuestionAnsweringSystem

private List<Evidence> search(String query) {
  List<Evidence> evidences = new ArrayList<>();
  try {
    HttpClient httpClient = new HttpClient();
    GetMethod getMethod = new GetMethod(query);
        new DefaultHttpMethodRetryHandler());
    int statusCode = httpClient.executeMethod(getMethod);
    if (statusCode != HttpStatus.SC_OK) {
      LOG.error("Method failed: " + getMethod.getStatusLine());

代码示例来源:origin: ysc/QuestionAnsweringSystem

hcf.setProxy("127.0.0.1", 8087);
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(query);
httpClient.executeMethod(getMethod);
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
    new DefaultHttpMethodRetryHandler());
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
  LOG.error("Method failed: " + getMethod.getStatusLine());

代码示例来源:origin: jenkinsci/jenkins

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);
int code = client.executeMethod(method);
if (code != HttpURLConnection.HTTP_OK) {
  return FormValidation.error(Messages.ProxyConfiguration_FailedToConnect(testUrl, code));

代码示例来源:origin: Alluxio/alluxio

/**
 * Uses the post method to send a url with arguments by http, this method can call RESTful Api.
 *
 * @param url the http url
 * @param timeout milliseconds to wait for the server to respond before giving up
 * @param processInputStream the response body stream processor
 */
public static void post(String url, Integer timeout,
            IProcessInputStream processInputStream)
  throws IOException {
 Preconditions.checkNotNull(timeout, "timeout");
 Preconditions.checkNotNull(processInputStream, "processInputStream");
 PostMethod postMethod = new PostMethod(url);
 try {
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
  httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
  int statusCode = httpClient.executeMethod(postMethod);
  if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
   InputStream inputStream = postMethod.getResponseBodyAsStream();
   processInputStream.process(inputStream);
  } else {
   throw new IOException("Failed to perform POST request. Status code: " + statusCode);
  }
 } finally {
  postMethod.releaseConnection();
 }
}

代码示例来源:origin: apache/incubator-pinot

public static PostMethod sendMultipartPostRequest(String url, String body)
  throws IOException {
 HttpClient httpClient = new HttpClient();
 PostMethod postMethod = new PostMethod(url);
 // our handlers ignore key...so we can put anything here
 Part[] parts = {new StringPart("body", body)};
 postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
 httpClient.executeMethod(postMethod);
 return postMethod;
}

代码示例来源:origin: openhab/openhab1-addons

String proxyPassword, String nonProxyHosts) {
HttpClient client = new HttpClient();
  int statusCode = client.executeMethod(method);
  if (statusCode != HttpStatus.SC_OK) {
    logger.debug("Method failed: {}", method.getStatusLine());

代码示例来源:origin: apache/incubator-pinot

public static PutMethod sendMultipartPutRequest(String url, String body)
   throws IOException {
  HttpClient httpClient = new HttpClient();
  PutMethod putMethod = new PutMethod(url);
  // our handlers ignore key...so we can put anything here
  Part[] parts = {new StringPart("body", body)};
  putMethod.setRequestEntity(new MultipartRequestEntity(parts, putMethod.getParams()));
  httpClient.executeMethod(putMethod);
  return putMethod;
 }
}

代码示例来源: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: apache/cloudstack

/**
 * Makes an api call using region service end_point, api command and params
 * @param region
 * @param command
 * @param params
 * @return True, if api is successful
 */
protected static boolean makeAPICall(Region region, String command, List<NameValuePair> params) {
  try {
    String apiParams = buildParams(command, params);
    String url = buildUrl(apiParams, region);
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    if (client.executeMethod(method) == 200) {
      return true;
    } else {
      return false;
    }
  } catch (HttpException e) {
    s_logger.error(e.getMessage());
    return false;
  } catch (IOException e) {
    s_logger.error(e.getMessage());
    return false;
  }
}

代码示例来源:origin: KylinOLAP/Kylin

private String getHttpResponse(String url) throws IOException {
  HttpClient client = new HttpClient();
      client.executeMethod(get);

代码示例来源: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());

代码示例来源: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());

代码示例来源: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();

代码示例来源:origin: KylinOLAP/Kylin

HttpClient httpClient = new HttpClient();
if (conn.getQueryUrl().toLowerCase().startsWith("https://")) {
  registerSsl();
  post.setRequestEntity(requestEntity);
  httpClient.executeMethod(post);
  response = post.getResponseBodyAsString();

代码示例来源: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: KylinOLAP/Kylin

@Override
public void connect() throws ConnectionException {
  PostMethod post = new PostMethod(conn.getConnectUrl());
  HttpClient httpClient = new HttpClient();
  if (conn.getConnectUrl().toLowerCase().startsWith("https://")) {
    registerSsl();
  }
  addPostHeaders(post);
  try {
    StringRequestEntity requestEntity = new StringRequestEntity("{}", "application/json", "UTF-8");
    post.setRequestEntity(requestEntity);
    httpClient.executeMethod(post);
    if (post.getStatusCode() != 200 && post.getStatusCode() != 201) {
      logger.error("Connect failed with error code " + post.getStatusCode() + " and message:\n" + post.getResponseBodyAsString());
      throw new ConnectionException("Connect failed, error code " + post.getStatusCode() + " and message: " + post.getResponseBodyAsString());
    }
  } catch (HttpException e) {
    logger.error(e.getLocalizedMessage(), e);
    throw new ConnectionException(e.getLocalizedMessage());
  } catch (IOException e) {
    logger.error(e.getLocalizedMessage(), e);
    throw new ConnectionException(e.getLocalizedMessage());
  }
}

代码示例来源:origin: KylinOLAP/Kylin

@Override
public KylinMetaImpl.MetaProject getMetadata(String project) throws ConnectionException {
  GetMethod get = new GetMethod(conn.getMetaProjectUrl(project));
  HttpClient httpClient = new HttpClient();
    httpClient.executeMethod(get);

代码示例来源:origin: naver/ngrinder

@Ignore
  @Test
  public void testRestAPI() throws IOException {
    HttpClient client = new HttpClient();
    // To be avoided unless in debug mode
    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "111111");
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);
    PutMethod method = new PutMethod("http://localhost:8080/agent/api/36");
    final HttpMethodParams params = new HttpMethodParams();
    params.setParameter("action", "approve");
    method.setParams(params);
    final int i = client.executeMethod(method);
    System.out.println(method.getResponseBodyAsString());
  }
}

相关文章