co.cask.common.http.HttpRequest类的使用及代码示例

x33g5p2x  于2022-01-20 转载在 其他  
字(13.5k)|赞(0)|评价(0)|浏览(88)

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

HttpRequest介绍

暂无

代码示例

代码示例来源:origin: co.cask.cdap/cdap-authentication-client

private AccessToken fetchAccessToken() throws IOException {
 LOG.debug("Authentication is enabled in the gateway server. Authentication URI {}.", getAuthURI());
 return execute(HttpRequest.get(getAuthURI().toURL())
          .addHeaders(getAuthenticationHeaders())
          .build()
 );
}

代码示例来源:origin: stackoverflow.com

YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
  public void initialize(HttpRequest request) throws IOException {
    request.put("Authorization", "Bearer " + yourAccessTokenString);
  }
}).setApplicationName("AppName").build();

代码示例来源:origin: caskdata/cdap

/**
 * Create a {@link HttpRequest.Builder} using the specified http method and resource. This client will
 * discover the service address and combine the specified resource in order to set a URL for the builder.
 *
 * @param method the request method
 * @param resource the request resource
 * @return a builder to create the http request, with method and URL already set
 */
public HttpRequest.Builder requestBuilder(HttpMethod method, String resource) {
 return HttpRequest.builder(method, resolve(resource));
}

代码示例来源:origin: caskdata/cdap

/**
  * Create a generic error message about a failure to make a specified request.
  *
  * @param request the request made
  * @param body the request body if it should be in the error message
  * @return a generic error message about the failure
  */
 public String createErrorMessage(HttpRequest request, @Nullable String body) {
  String headers = request.getHeaders() == null ?
   "null" : Joiner.on(",").withKeyValueSeparator("=").join(request.getHeaders().entries());
  return String.format("Error making request to %s service at %s while doing %s with headers %s%s.",
             discoverableServiceName, request.getURL(), request.getMethod(),
             headers, body == null ? "" : " and body " + body);
 }
}

代码示例来源:origin: co.cask.cdap/cdap-notifications-api

private HttpResponse execute(HttpRequest request) throws NotificationFeedException {
  try {
   return remoteClient.execute(request);
  } catch (IOException e) {
   throw new NotificationFeedException(
    String.format("Error connecting to Notification Feed Service at %s while doing %s",
           request.getURL(), request.getMethod()));
  }
 }
}

代码示例来源:origin: cdapio/cdap

HttpResponse response = HttpRequests.execute(HttpRequest.get(serviceURI.resolve("exists/nn").toURL()).build());
Assert.assertEquals(200, response.getResponseCode());
Assert.assertEquals("false", response.getResponseBodyAsString());
response = HttpRequests.execute(HttpRequest.put(serviceURI.resolve("create/nn/table").toURL()).build());
Assert.assertEquals(200, response.getResponseCode());
response = HttpRequests.execute(HttpRequest.get(serviceURI.resolve("exists/nn").toURL()).build());
Assert.assertEquals(200, response.getResponseCode());
Assert.assertEquals("true", response.getResponseBodyAsString());
response = HttpRequests.execute(HttpRequest.put(serviceURI.resolve("create/nn/fileSet").toURL()).build());
Assert.assertEquals(409, response.getResponseCode());
response = HttpRequests.execute(HttpRequest.get(serviceURI.resolve("type/xx").toURL()).build());
Assert.assertEquals(404, response.getResponseCode());
response = HttpRequests.execute(HttpRequest.get(serviceURI.resolve("type/nn").toURL()).build());
Assert.assertEquals(200, response.getResponseCode());
Assert.assertEquals("table", response.getResponseBodyAsString());
response = HttpRequests.execute(HttpRequest.put(serviceURI.resolve("update/xx").toURL())
                 .withBody(GSON.toJson(nnProps)).build());
Assert.assertEquals(404, response.getResponseCode());
response = HttpRequests.execute(HttpRequest.put(serviceURI.resolve("update/nn").toURL())
                 .withBody(GSON.toJson(nnProps)).build());
Assert.assertEquals(200, response.getResponseCode());

代码示例来源:origin: caskdata/cdap

@Override
public void dropRole(Role role) throws IOException, FeatureDisabledException, UnauthenticatedException,
 UnauthorizedException, NotFoundException, co.cask.cdap.security.spi.authorization.NotFoundException {
 URL url = config.resolveURLV3(String.format(AUTHORIZATION_BASE + "roles/%s", role.getName()));
 HttpRequest request = HttpRequest.delete(url).build();
 executeExistingRolesRequest(role, request);
}

代码示例来源:origin: cdapio/cdap

HttpResponse response;
try {
 request = HttpRequest.post(url).withBody(text).build();
 response = HttpRequests.execute(request);
url = new URL(pfsURL, apiPath);
try  {
 request = HttpRequest.post(url).withBody(text).build();
 response = HttpRequests.execute(request);
 request = HttpRequest.get(url).build();
 response = HttpRequests.execute(request);
 Assert.assertEquals(200, response.getResponseCode());
 Assert.assertEquals(text, response.getResponseBodyAsString());
 request = HttpRequest.delete(url).build();
 response = HttpRequests.execute(request);
 Assert.assertEquals(200, response.getResponseCode());

代码示例来源:origin: caskdata/cdap

private void revoke(RevokeRequest revokeRequest)
 throws IOException, UnauthenticatedException, FeatureDisabledException, UnauthorizedException, NotFoundException {
 URL url = config.resolveURLV3(AUTHORIZATION_BASE + "/privileges/revoke");
 HttpRequest request = HttpRequest.post(url).withBody(GSON.toJson(revokeRequest)).build();
 executePrivilegeRequest(request);
}

代码示例来源:origin: cdapio/cdap

/**
 * This test the normal operations of the SOCKS proxy.
 */
@Test
public void testSocksProxy() throws Exception {
 InetSocketAddress httpAddr = httpService.getBindAddress();
 // Make 10 requests. With connection keep-alive, there should only be one SSH tunnel created
 URL url = new URL(String.format("http://%s:%d/ping", httpAddr.getHostName(), httpAddr.getPort()));
 for (int i = 0; i < 10; i++) {
  HttpResponse response = HttpRequests.execute(co.cask.common.http.HttpRequest.get(url).build());
  Assert.assertEquals(200, response.getResponseCode());
 }
 Assert.assertEquals(1, sshSession.portForwardCreated.get());
 // Make one more call with Connection: close. This should close the connection, hence close the tunnel.
 HttpResponse response = HttpRequests.execute(
  co.cask.common.http.HttpRequest.builder(HttpMethod.GET, url)
   .addHeader(HttpHeaderNames.CONNECTION.toString(), HttpHeaderValues.CLOSE.toString())
   .build());
 Assert.assertEquals(200, response.getResponseCode());
 Assert.assertEquals(1, sshSession.portForwardCreated.get());
 Tasks.waitFor(1, () -> sshSession.portForwardClosed.get(), 5, TimeUnit.SECONDS, 100, TimeUnit.MILLISECONDS);
}

代码示例来源:origin: cdapio/cdap

@Category(XSlowTests.class)
@Test
public void testByteCodeClassLoader() throws Exception {
 // This test verify bytecode generated classes ClassLoading
 ApplicationManager appManager = deployApplication(testSpace, ClassLoaderTestApp.class);
 ServiceManager serviceManager = appManager.getServiceManager("RecordHandler").start();
 URL serviceURL = serviceManager.getServiceURL(15, TimeUnit.SECONDS);
 Assert.assertNotNull(serviceURL);
 // Increment record
 URL url = new URL(serviceURL, "increment/public");
 for (int i = 0; i < 10; i++) {
  HttpResponse response = HttpRequests.execute(HttpRequest.post(url).build());
  Assert.assertEquals(200, response.getResponseCode());
 }
 // Query record
 url = new URL(serviceURL, "query?type=public");
 HttpRequest request = HttpRequest.get(url).build();
 HttpResponse response = HttpRequests.execute(request);
 Assert.assertEquals(200, response.getResponseCode());
 long count = Long.parseLong(response.getResponseBodyAsString());
 serviceManager.stop();
 // Verify the record count with dataset
 DataSetManager<KeyValueTable> recordsManager = getDataset(testSpace.dataset("records"));
 KeyValueTable records = recordsManager.get();
 Assert.assertEquals(count, Bytes.toLong(records.read("PUBLIC")));
}

代码示例来源:origin: cdapio/cdap

private HttpResponse executeRequest(ImpersonationRequest impersonationRequest) throws IOException {
 HttpRequest request = remoteClient.requestBuilder(HttpMethod.POST, "impersonation/credentials")
  .withBody(GSON.toJson(impersonationRequest))
  .build();
 HttpResponse response = remoteClient.execute(request);
 if (response.getResponseCode() == HttpURLConnection.HTTP_OK) {
  return response;
 }
 throw new IOException(String.format("%s Response: %s.", createErrorMessage(request.getURL()), response));
}

代码示例来源:origin: caskdata/cdap

@Override
public void removeRoleFromPrincipal(Role role, Principal principal) throws IOException, FeatureDisabledException,
 UnauthenticatedException, UnauthorizedException, NotFoundException,
 co.cask.cdap.security.spi.authorization.NotFoundException {
 URL url = config.resolveURLV3(String.format(AUTHORIZATION_BASE + "%s/%s/roles/%s", principal.getType(),
                       principal.getName(), role.getName()));
 HttpRequest request = HttpRequest.delete(url).build();
 executeExistingRolesRequest(role, request);
}

代码示例来源:origin: caskdata/cdap

@Override
public void grant(Authorizable authorizable, Principal principal, Set<Action> actions) throws IOException,
 UnauthorizedException, UnauthenticatedException, NotFoundException, FeatureDisabledException {
 GrantRequest grantRequest = new GrantRequest(authorizable, principal, actions);
 URL url = config.resolveURLV3(AUTHORIZATION_BASE + "/privileges/grant");
 HttpRequest request = HttpRequest.post(url).withBody(GSON.toJson(grantRequest)).build();
 executePrivilegeRequest(request);
}

代码示例来源:origin: co.cask.cdap/cdap-data-fabric

private HttpResponse doRequest(HttpRequest.Builder requestBuilder) throws DatasetManagementException {
 HttpRequest request = addUserIdHeader(requestBuilder).build();
 try {
  LOG.trace("Executing {} {}", request.getMethod(), request.getURL().getPath());
  HttpResponse response = remoteClient.execute(request);
  LOG.trace("Executed {} {}", request.getMethod(), request.getURL().getPath());
  return response;
 } catch (ServiceUnavailableException e) { // thrown by RemoteClient in case of ConnectException
  logThreadDump();
  LOG.trace("Caught exception for {} {}", request.getMethod(), request.getURL().getPath(), e);
  throw e;
 } catch (SocketTimeoutException e) { // passed through by RemoteClient
  logThreadDump();
  LOG.trace("Caught exception for {} {}", request.getMethod(), request.getURL().getPath(), e);
  throw new DatasetManagementException(remoteClient.createErrorMessage(request, null), e);
 } catch (IOException e) { // other network exceptions
  LOG.trace("Caught exception for {} {}", request.getMethod(), request.getURL().getPath(), e);
  throw new DatasetManagementException(remoteClient.createErrorMessage(request, null), e);
 } catch (Throwable e) { // anything unexpected
  LOG.trace("Caught exception for {} {}", request.getMethod(), request.getURL().getPath(), e);
  throw e;
 }
}

代码示例来源:origin: co.cask.cdap/cdap-common

/**
  * Create a generic error message about a failure to make a specified request.
  *
  * @param request the request made
  * @param body the request body if it should be in the error message
  * @return a generic error message about the failure
  */
 public String createErrorMessage(HttpRequest request, @Nullable String body) {
  String headers = request.getHeaders() == null ?
   "null" : Joiner.on(",").withKeyValueSeparator("=").join(request.getHeaders().entries());
  return String.format("Error making request to %s service at %s while doing %s with headers %s%s.",
             discoverableServiceName, request.getURL(), request.getMethod(),
             headers, body == null ? "" : " and body " + body);
 }
}

代码示例来源:origin: caskdata/cdap

@Override
public List<NamespaceMeta> list() throws Exception {
 HttpRequest request = HttpRequest.get(resolve("namespaces")).build();
 HttpResponse response = execute(request);
 if (response.getResponseCode() == HttpURLConnection.HTTP_OK) {
  return ObjectResponse.fromJsonBody(response, new TypeToken<List<NamespaceMeta>>() { }).getResponseObject();
 }
 throw new IOException(String.format("Cannot list namespaces. Reason: %s", response.getResponseBodyAsString()));
}

代码示例来源:origin: caskdata/cdap

@Override
public void updateProperties(NamespaceId namespaceId, NamespaceMeta metadata) throws Exception {
 URL url = resolve(String.format("namespaces/%s/properties", namespaceId.getNamespace()));
 HttpResponse response = execute(HttpRequest.put(url).withBody(GSON.toJson(metadata)).build());
 String responseBody = response.getResponseBodyAsString();
 if (response.getResponseCode() == HttpURLConnection.HTTP_OK) {
  return;
 }
 if (response.getResponseCode() == HttpURLConnection.HTTP_BAD_REQUEST) {
  throw new BadRequestException("Bad request: " + responseBody);
 }
 throw new IOException(String.format("Cannot update namespace %s. Reason: %s", namespaceId, responseBody));
}

代码示例来源:origin: co.cask.cdap/cdap-common

/**
 * Create a {@link HttpRequest.Builder} using the specified http method and resource. This client will
 * discover the service address and combine the specified resource in order to set a URL for the builder.
 *
 * @param method the request method
 * @param resource the request resource
 * @return a builder to create the http request, with method and URL already set
 */
public HttpRequest.Builder requestBuilder(HttpMethod method, String resource) {
 return HttpRequest.builder(method, resolve(resource));
}

代码示例来源:origin: caskdata/cdap

@Override
public void deleteDatasets(NamespaceId namespaceId) throws Exception {
 URL url = resolve(String.format("unrecoverable/namespaces/%s/datasets", namespaceId.getNamespace()));
 HttpResponse response = execute(HttpRequest.delete(url).build());
 if (response.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
  throw new NamespaceNotFoundException(namespaceId);
 } else if (HttpURLConnection.HTTP_FORBIDDEN == response.getResponseCode()) {
  String msg = String.format("Datasets in the namespace '%s' cannot be deleted. Reason: '%s'.", namespaceId,
                response.getResponseBodyAsString());
  throw new NamespaceCannotBeDeletedException(namespaceId, msg);
 } else if (response.getResponseCode() == HttpURLConnection.HTTP_OK) {
  return;
 }
 throw new IOException(String.format("Cannot delete datasets in namespace %s. Reason: %s",
                   namespaceId, response.getResponseBodyAsString()));
}

相关文章