类org.apache.http.client.fluent.Response源码实例Demo

下面列出了怎么用org.apache.http.client.fluent.Response的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: android-uiconductor   文件: HttpProxyUtils.java
public static String postRequestAsString(String url, String request)
    throws UicdDeviceHttpConnectionResetException {
  logger.info("post request to xmldumper:" + url);
  String ret = "";
  Response response = null;
  try {
    response = Request.Post(url)
        .body(new StringEntity(request))
        .execute();
    ret = response.returnContent().asString(Consts.UTF_8);
  } catch (IOException e) {
    logger.severe(e.getMessage());
    // See comments in getRequestAsString
    if (CONNECTION_RESET_KEYWORDS_LIST.stream().parallel().anyMatch(e.getMessage()::contains)) {
      throw new UicdDeviceHttpConnectionResetException(e.getMessage());
    }
  }
  logger.info("return from xmldumper:" + ret);
  return ret;
}
 
public SoapRawClientResponse callSoapService(InputStream xmlFile) throws InternalBusinessException {
	SoapRawClientResponse rawSoapResponse = new SoapRawClientResponse();
	
	LOGGER.debug("Calling SoapService with POST on Apache HTTP-Client and configured URL: {}", soapServiceUrl);
	
	try {
		Response httpResponseContainer = Request
				.Post(soapServiceUrl)
				.bodyStream(xmlFile, contentTypeTextXmlUtf8())
				.addHeader("SOAPAction", "\"" + soapAction + "\"")
				.execute();
		
		HttpResponse httpResponse = httpResponseContainer.returnResponse();			
		rawSoapResponse.setHttpStatusCode(httpResponse.getStatusLine().getStatusCode());
		rawSoapResponse.setHttpResponseBody(XmlUtils.parseFileStream2Document(httpResponse.getEntity().getContent()));
		
	} catch (Exception exception) {
		throw new InternalBusinessException("Some Error accured while trying to Call SoapService for test: " + exception.getMessage());
	}		
	return rawSoapResponse;
}
 
@Test
public void shouldRespondWithNotImplemented() throws Exception {
    wireMockRule.stubFor(any(urlEqualTo("/team/my_team"))
            .willReturn(aResponse().withStatus(HttpStatus.SC_NOT_IMPLEMENTED)));


    Request request = Request.Get("http://localhost:8082/test/my_team");

    // A little bit of reflection to set an unknown HTTP method since the fluent API does not allow it.
    Field requestField = request.getClass().getDeclaredField("request");
    requestField.setAccessible(true);
    Field methodField = requestField.get(request).getClass().getDeclaredField("method");
    methodField.setAccessible(true);
    methodField.set(requestField.get(request), "unkown-method");

    Response response = request.execute();
    HttpResponse returnResponse = response.returnResponse();

    assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, returnResponse.getStatusLine().getStatusCode());

    wireMockRule.verify(anyRequestedFor(urlPathEqualTo("/team/my_team")));
}
 
@Test
public void call_weighted_lb_multiple_endpoints() throws Exception {
    wireMockRule.stubFor(get(urlEqualTo("/api1")).willReturn(ok()));
    wireMockRule.stubFor(get(urlEqualTo("/api2")).willReturn(ok()));

    Request request = Request.Get("http://localhost:8082/api");

    int calls = 10;

    for(int i = 0 ; i < calls ; i++) {
        Response response = request.execute();
        HttpResponse returnResponse = response.returnResponse();

        assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode());
    }

    wireMockRule.verify(3, getRequestedFor(urlPathEqualTo("/api1")));
    wireMockRule.verify(7, getRequestedFor(urlPathEqualTo("/api2")));
}
 
源代码5 项目: gravitee-gateway   文件: PostContentGatewayTest.java
@Test
public void no_content_without_chunked_encoding_transfer() throws Exception {
    stubFor(post(urlEqualTo("/team/my_team")).willReturn(ok()));

    Request request = Request.Post("http://localhost:8082/test/my_team")
            .addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
            .removeHeaders(HttpHeaders.TRANSFER_ENCODING);

    Response response = request.execute();

    HttpResponse returnResponse = response.returnResponse();
    assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode());

    // Set chunk mode in request but returns raw because of the size of the content
    assertEquals(null, returnResponse.getFirstHeader("X-Forwarded-Transfer-Encoding"));

    String responseContent = StringUtils.copy(returnResponse.getEntity().getContent());
    assertEquals(0, responseContent.length());

    verify(postRequestedFor(urlEqualTo("/team/my_team"))
            .withoutHeader(HttpHeaders.TRANSFER_ENCODING)
            .withHeader(io.gravitee.common.http.HttpHeaders.CONTENT_TYPE, new EqualToPattern(MediaType.APPLICATION_JSON)));
}
 
源代码6 项目: gravitee-gateway   文件: PostContentGatewayTest.java
@Test
public void get_no_content_with_chunked_encoding_transfer() throws Exception {
    stubFor(get(urlEqualTo("/team/my_team")).willReturn(ok()));

    Request request = Request.Get("http://localhost:8082/test/my_team")
            .addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
            .removeHeaders(HttpHeaders.TRANSFER_ENCODING);

    Response response = request.execute();

    HttpResponse returnResponse = response.returnResponse();
    assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode());

    // Set chunk mode in request but returns raw because of the size of the content
    assertEquals(null, returnResponse.getFirstHeader("X-Forwarded-Transfer-Encoding"));

    String responseContent = StringUtils.copy(returnResponse.getEntity().getContent());
    assertEquals(0, responseContent.length());

    verify(getRequestedFor(urlEqualTo("/team/my_team"))
            .withoutHeader(HttpHeaders.TRANSFER_ENCODING)
            .withHeader(io.gravitee.common.http.HttpHeaders.CONTENT_TYPE, new EqualToPattern(MediaType.APPLICATION_JSON)));
}
 
源代码7 项目: gravitee-gateway   文件: PostContentGatewayTest.java
@Test
public void get_no_content_with_chunked_encoding_transfer_and_content_type() throws Exception {
    stubFor(get(urlEqualTo("/team/my_team")).willReturn(ok()));

    Request request = Request.Get("http://localhost:8082/test/my_team")
            .addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);

    Response response = request.execute();

    HttpResponse returnResponse = response.returnResponse();
    assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode());

    // Set chunk mode in request but returns raw because of the size of the content
    assertEquals(null, returnResponse.getFirstHeader("X-Forwarded-Transfer-Encoding"));

    String responseContent = StringUtils.copy(returnResponse.getEntity().getContent());
    assertEquals(0, responseContent.length());

    verify(getRequestedFor(urlEqualTo("/team/my_team"))
            .withHeader(io.gravitee.common.http.HttpHeaders.CONTENT_TYPE, new EqualToPattern(MediaType.APPLICATION_JSON)));
}
 
protected boolean delete(String deleteJobUrl) throws IOException {
    boolean rc = false;
    String sReturn = "";

    Request request = Request
            .Delete(deleteJobUrl)
            .addHeader(AUTH.WWW_AUTH_RESP, getAuthorization())
            .useExpectContinue();

    Response response = executor.execute(request);
    HttpResponse hResponse = response.returnResponse();
    int rcResponse = hResponse.getStatusLine().getStatusCode();

    if (HttpStatus.SC_OK == rcResponse) {
        sReturn = EntityUtils.toString(hResponse.getEntity());
        rc = true;
    } else {
        rc = false;
    }
    traceLog.finest("Request: [" + deleteJobUrl + "]");
    traceLog.finest(rcResponse + ": " + sReturn);
    return rc;
}
 
源代码9 项目: kurento-tutorial-java   文件: OrionConnector.java
/**
 * Sends a request to Orion
 *
 * @param ctxElement
 *          The context element
 * @param path
 *          the path from the context broker that determines which "operation"will be executed
 * @param responseClazz
 *          The class expected for the response
 * @return The object representing the JSON answer from Orion
 * @throws OrionConnectorException
 *           if a communication exception happens, either when contacting the context broker at
 *           the given address, or obtaining the answer from it.
 */
private <E, T> T sendRequestToOrion(E ctxElement, String path, Class<T> responseClazz) {
  String jsonEntity = gson.toJson(ctxElement);
  log.debug("Send request to Orion: {}", jsonEntity);

  Request req = Request.Post(this.orionAddr.toString() + path)
      .addHeader("Accept", APPLICATION_JSON.getMimeType())
      .bodyString(jsonEntity, APPLICATION_JSON).connectTimeout(5000).socketTimeout(5000);
  Response response;
  try {
    response = req.execute();
  } catch (IOException e) {
    throw new OrionConnectorException("Could not execute HTTP request", e);
  }

  HttpResponse httpResponse = checkResponse(response);

  T ctxResp = getOrionObjFromResponse(httpResponse, responseClazz);
  log.debug("Sent to Orion. Obtained response: {}", httpResponse);

  return ctxResp;
}
 
源代码10 项目: java-specialagent   文件: HttpServiceTest.java
@Test
// @AgentRunner.TestConfig(verbose = true)
public void httpServiceTest(final MockTracer tracer) throws Exception {
  final Response response = Request.Get("http://" + HOST + ":" + PORT + "/").execute();
  assertEquals(response.returnResponse().getStatusLine().getStatusCode(), 503);
  assertEquals(1, tracer.finishedSpans().size());
}
 
源代码11 项目: JSONParser   文件: JSONParserTest.java
private String getJSON() throws IOException {
    String url = "http://music.163.com/weapi/v3/playlist/detail";
    List<BasicNameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("params", "kJMudgZJvK8p8STuuxRpkUvO71Enw4C9y91PBkVTv2SMVnWG30eDKK1iAPcXnEah"));
    params.add(new BasicNameValuePair("encSecKey", "d09b0b95b7d5b4e68aa7a16d6177d3f00a78bfa013ba59f309d41f18a2b4ea066cdea7863866b6283f403ddcd3bfb51f73f8ad3c6818269ceabff934a645196faf7a9aae0edde6e232b279fd495140e6252503291cf819eabbd9f3373648775201a70f179b7981d627257d3bba5a5e1b99d0732ce3e898db3614d82bcbe1a6a8"));
    Response response = Request.Post(url)
            .bodyForm(params)
            .execute();

    return response.returnContent().asString(Charset.forName("utf-8"));
}
 
源代码12 项目: hudi   文件: RemoteHoodieTableFileSystemView.java
private <T> T executeRequest(String requestPath, Map<String, String> queryParameters, TypeReference reference,
    RequestMethod method) throws IOException {
  ValidationUtils.checkArgument(!closed, "View already closed");

  URIBuilder builder =
      new URIBuilder().setHost(serverHost).setPort(serverPort).setPath(requestPath).setScheme("http");

  queryParameters.forEach(builder::addParameter);

  // Adding mandatory parameters - Last instants affecting file-slice
  timeline.lastInstant().ifPresent(instant -> builder.addParameter(LAST_INSTANT_TS, instant.getTimestamp()));
  builder.addParameter(TIMELINE_HASH, timeline.getTimelineHash());

  String url = builder.toString();
  LOG.info("Sending request : (" + url + ")");
  Response response;
  int timeout = 1000 * 300; // 5 min timeout
  switch (method) {
    case GET:
      response = Request.Get(url).connectTimeout(timeout).socketTimeout(timeout).execute();
      break;
    case POST:
    default:
      response = Request.Post(url).connectTimeout(timeout).socketTimeout(timeout).execute();
      break;
  }
  String content = response.returnContent().asString();
  return mapper.readValue(content, reference);
}
 
源代码13 项目: thorntail   文件: MvcTest.java
@Test
@RunAsClient
public void testGettingView() throws IOException {
    Response response = Request.Get(baseUrl.toString() + "/hello").execute();
    Content content = response.returnContent();
    assertThat(content.asString(), containsString("Hello World!"));
}
 
源代码14 项目: gravitee-gateway   文件: UnfollowRedirectTest.java
@Test
public void shouldNotFollowRedirect() throws Exception {
    wireMockRule.stubFor(get("/redirect").willReturn(permanentRedirect("http://localhost:" + wireMockRule.port() + "/final")));

    HttpClient client = HttpClientBuilder.create().disableRedirectHandling().build();

    Request request = Request.Get("http://localhost:8082/api/redirect");
    Response response = Executor.newInstance(client).execute(request);
    HttpResponse returnResponse = response.returnResponse();

    assertEquals(HttpStatus.SC_MOVED_PERMANENTLY, returnResponse.getStatusLine().getStatusCode());

    wireMockRule.verify(1, getRequestedFor(urlPathEqualTo("/redirect")));
    wireMockRule.verify(0, getRequestedFor(urlPathEqualTo("/final")));
}
 
源代码15 项目: james-project   文件: DownloadStepdefs.java
private void trustForBlobId(String blobId, String username) throws Exception {
    Response tokenGenerationResponse = Request.Post(baseUri(mainStepdefs.jmapServer).setPath("/download/" + blobId).build())
        .addHeader("Authorization", userStepdefs.authenticate(username).asString())
        .execute();
    String serializedAttachmentAccessToken = tokenGenerationResponse.returnContent().asString();
    attachmentAccessTokens.put(
            new AttachmentAccessTokenKey(username, blobId),
            AttachmentAccessToken.from(
                serializedAttachmentAccessToken,
                blobId));
}
 
源代码16 项目: james-project   文件: ContainerTest.java
@Test
public void containerShouldBeReachableOnExposedPort() throws IOException, URISyntaxException {
    Response response = Request.Get(new URIBuilder()
        .setScheme("http")
        .setHost(container.getHostIp())
        .setPort(container.getMappedPort(80)).build())
        .execute();

    assertThat(response.returnResponse().getStatusLine().getStatusCode())
        .isEqualTo(200);
}
 
源代码17 项目: james-project   文件: HttpJmapAuthentication.java
public static AccessToken doAuthenticate(URIBuilder uriBuilder, Username username, String password) throws ClientProtocolException, IOException, URISyntaxException {
    String continuationToken = getContinuationToken(uriBuilder, username);

    Response response = postAuthenticate(uriBuilder, password, continuationToken);

    return AccessToken.of(
        JsonPath.parse(response.returnContent().asString())
            .read("accessToken"));
}
 
源代码18 项目: james-project   文件: HttpJmapAuthentication.java
private static Response postAuthenticate(URIBuilder uriBuilder, String password, String continuationToken) throws ClientProtocolException, IOException, URISyntaxException {
    return Request.Post(uriBuilder.setPath("/authentication").build())
            .bodyString("{\"token\": \"" + continuationToken + "\", \"method\": \"password\", \"password\": \"" + password + "\"}", 
                    ContentType.APPLICATION_JSON)
            .setHeader("Accept", ContentType.APPLICATION_JSON.getMimeType())
            .execute();
}
 
源代码19 项目: james-project   文件: HttpJmapAuthentication.java
private static String getContinuationToken(URIBuilder uriBuilder, Username username) throws ClientProtocolException, IOException, URISyntaxException {
    Response response = Request.Post(uriBuilder.setPath("/authentication").build())
        .bodyString("{\"username\": \"" + username.asString() + "\", \"clientName\": \"Mozilla Thunderbird\", \"clientVersion\": \"42.0\", \"deviceName\": \"Joe Blogg’s iPhone\"}",
            ContentType.APPLICATION_JSON)
        .setHeader("Accept", ContentType.APPLICATION_JSON.getMimeType())
        .execute();

    return JsonPath.parse(response.returnContent().asString())
        .read("continuationToken");
}
 
源代码20 项目: streamsx.topology   文件: StreamsRestUtils.java
private static InputStream rawStreamingGet(Executor executor,
        String auth, String url) throws IOException {
    TRACE.fine("HTTP GET: " + url);
    String accepted =
            ContentType.APPLICATION_OCTET_STREAM.getMimeType()
            + ","
            + "application/x-compressed";
    Request request = Request
            .Get(url)
            .addHeader("accept",accepted)
            .useExpectContinue();
    
    if (null != auth) {
        request = request.addHeader(AUTH.WWW_AUTH_RESP, auth);
    }
    
    Response response = executor.execute(request);
    HttpResponse hResponse = response.returnResponse();
    int rcResponse = hResponse.getStatusLine().getStatusCode();
    
    if (HttpStatus.SC_OK == rcResponse) {
        return hResponse.getEntity().getContent();
    } else {
        // all other errors...
        String httpError = "HttpStatus is " + rcResponse + " for url " + url;
        throw new RESTException(rcResponse, httpError);
    }
}
 
源代码21 项目: streamsx.topology   文件: StreamsRestActions.java
static Toolkit uploadToolkit(StreamsBuildService connection, File path) throws IOException {
  // Make sure it is a directory
  if (! path.isDirectory()) {
    throw new IllegalArgumentException("The specified toolkit path '" + path.toString() + "' is not a directory.");
  }

  // Make sure it contains toolkit.xml
  File toolkit = new File(path, "toolkit.xml");
  if (! toolkit.isFile()) {
    throw new IllegalArgumentException("The specified toolkit path '" + path.toString() + "' is not a toolkit.");
  }

  String toolkitsURL = connection.getToolkitsURL();
  Request post = Request.Post(toolkitsURL);
  post.addHeader(AUTH.WWW_AUTH_RESP, connection.getAuthorization());
  post.bodyStream(DirectoryZipInputStream.fromPath(path.toPath()), ContentType.create("application/zip"));

  Response response = connection.getExecutor().execute(post);
  HttpResponse httpResponse = response.returnResponse();
  int statusCode = httpResponse.getStatusLine().getStatusCode();
  // TODO The API is supposed to return CREATED, but there is a bug and it
  // returns OK.  When the bug is fixed, change this to accept only OK
  if (statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_OK) {
    String message = EntityUtils.toString(httpResponse.getEntity());
    throw RESTException.create(statusCode, message);
  }
  
  HttpEntity entity = httpResponse.getEntity();
  try (Reader r = new InputStreamReader(entity.getContent())) {
    JsonObject jresponse = new Gson().fromJson(r, JsonObject.class);
    EntityUtils.consume(entity);
    List<Toolkit> toolkitList = Toolkit.createToolkitList(connection, jresponse);

    // We expect a list of zero or one element.
    if (toolkitList.size() == 0) {
      return null;
    }
    return toolkitList.get(0);
  }
}
 
源代码22 项目: streamsx.topology   文件: StreamsRestActions.java
static boolean cancelJob(Instance instance, String jobId) throws IOException {
	Request deleteJob = Request.Delete(instance.self() + "/jobs/" + jobId);
	Response response = instance.connection().executor.execute(deleteJob);
	
	// TODO - error handling
	return true;
}
 
源代码23 项目: kurento-tutorial-java   文件: OrionConnector.java
private <T> HttpResponse checkResponse(Response response) {
  HttpResponse httpResponse;
  try {
    httpResponse = response.returnResponse();
  } catch (IOException e) {
    throw new OrionConnectorException("Could not obtain HTTP response", e);
  }

  if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
    throw new OrionConnectorException(
        "Failed with HTTP error code : " + httpResponse.getStatusLine().getStatusCode());
  }
  return httpResponse;
}
 
源代码24 项目: dcos-commons   文件: DcosHttpExecutor.java
/**
 * Runs the provided request and returns the response.
 */
public Response execute(Request request) throws IOException {
  return executor.execute(request);
}
 
源代码25 项目: thorntail   文件: NoAcceptHeadersTest.java
@Test
@RunAsClient
public void shouldGetMetricsWithoutAcceptHeadersSet() throws IOException {
    Response response = Request.Get("http://localhost:8080/metrics").execute();
    assertThat(response.returnResponse().getStatusLine().getStatusCode()).isEqualTo(200);
}
 
源代码26 项目: streamsx.topology   文件: StreamsRestUtils.java
/**
 * Gets a JSON response to an HTTP request call
 */
static JsonObject requestGsonResponse(Executor executor, Request request) throws IOException {
	request.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());
    Response response = executor.execute(request);
    return gsonFromResponse(response.returnResponse());
}
 
源代码27 项目: streamsx.topology   文件: RestUtils.java
/**
 * Gets a JSON response to an HTTP request call
 */
static JsonObject requestGsonResponse(Executor executor, Request request) throws IOException {
    request.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());
    Response response = executor.execute(request);
    return gsonFromResponse(response.returnResponse());
}
 
源代码28 项目: streamsx.topology   文件: StreamsRestUtils.java
/**
 * Gets a JSON response to an HTTP request call
 */
static JsonObject requestGsonResponse(Executor executor, Request request) throws IOException {
    request.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());
    Response response = executor.execute(request);
    return gsonFromResponse(response.returnResponse());
}
 
源代码29 项目: streamsx.topology   文件: StreamsRestUtils.java
static String requestTextResponse(Executor executor, Request request) throws IOException {
    request.addHeader("accept", ContentType.TEXT_PLAIN.getMimeType());
    Response response = executor.execute(request);
    return textFromResponse(response.returnResponse());
}
 
 类所在包
 类方法
 同包方法