Esempio n. 1
0
  public PingInfo ping(String host, int restPort, boolean noProxy) throws Exception {

    PingInfo myPingInfo = pingInfoProvider.createPingInfo();

    RequestConfig.Builder requestConfigBuilder =
        httpClientProvider.createRequestConfigBuilder(host, noProxy);

    String url = String.format(URL_PATTERN, host, restPort) + PingHandler.URL;
    HttpUriRequest request =
        RequestBuilder.post(url)
            .setConfig(requestConfigBuilder.build())
            .addParameter(PingHandler.PING_INFO_INPUT_NAME, gson.toJson(myPingInfo))
            .build();

    CloseableHttpResponse response = httpClientProvider.executeRequest(request);
    try {
      StatusLine statusLine = response.getStatusLine();
      if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
        EntityUtils.consumeQuietly(response.getEntity());
        throw new Exception(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
      }

      HttpEntity entity = response.getEntity();
      String content = EntityUtils.toString(entity);
      EntityUtils.consumeQuietly(entity);
      PingInfo receivedPingInfo = gson.fromJson(content, PingInfo.class);
      receivedPingInfo.getAgentId().setHost(request.getURI().getHost());
      return receivedPingInfo;
    } finally {
      response.close();
    }
  }
  public static void test1() throws ClientProtocolException, IOException {
    // httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("username", ""));
    formparams.add(new BasicNameValuePair("areacode", "86"));
    formparams.add(new BasicNameValuePair("telephone", "18782071219"));
    formparams.add(new BasicNameValuePair("remember_me", "1"));
    formparams.add(new BasicNameValuePair("password", Encoding.MD5("199337").toUpperCase()));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    HttpPost httppost = new HttpPost("http://xueqiu.com/user/login");
    httppost.setEntity(entity);
    httppost.setHeader("X-Requested-With", "XMLHttpRequest");
    CloseableHttpResponse httpResponse = httpClient.execute(httppost);
    HttpEntity entity1 = httpResponse.getEntity();
    if (entity1 != null) {
      System.out.println("--------------------------------------");
      System.out.println("Response content: " + EntityUtils.toString(entity1, "UTF-8"));
      System.out.println("--------------------------------------");
    }
    setCookieStore(httpResponse);
    HttpGet httpGet =
        new HttpGet(
            "http://xueqiu.com/financial_product/query.json?page=1&size=3&order=desc&orderby=SALEBEGINDATE&status=1&_=1439607538138");

    httpResponse = httpClient.execute(httpGet);
    entity1 = httpResponse.getEntity();
    if (entity1 != null) {
      System.out.println("--------------------------------------");
      System.out.println("Response content: " + EntityUtils.toString(entity1, "UTF-8"));
      System.out.println("--------------------------------------");
    }
  }
Esempio n. 3
0
  protected void putContent(String path, String content) throws Exception {
    String url = formatUrl(CONTENT_MGMT_PATH, path);
    HttpPut put = new HttpPut(url);
    put.setEntity(new StringEntity(content));

    CloseableHttpClient client = null;
    try {
      client = factory.createClient();
      CloseableHttpResponse response = client.execute(put);
      int code = response.getStatusLine().getStatusCode();
      if (code != 200 && code != 201) {
        String extra = "";
        if (response.getEntity() != null) {
          String body = IOUtils.toString(response.getEntity().getContent());
          extra = "\nBody:\n\n" + body;
        }

        Assert.fail(
            "Failed to put content to: "
                + path
                + ".\nURL: "
                + url
                + "\nStatus: "
                + response.getStatusLine()
                + extra);
      }
    } finally {
      IOUtils.closeQuietly(client);
    }
  }
 public static void main(String[] args) throws Exception {
   // 豌豆荚捕鱼达人的页面
   String url = "http://www.wandoujia.com/search?key=%E6%8D%95%E9%B1%BC%E8%BE%BE%E4%BA%BA";
   CloseableHttpClient client = HttpClients.createDefault();
   HttpGet httpGet = new HttpGet(url);
   CloseableHttpResponse response = client.execute(httpGet);
   HttpEntity entity = response.getEntity();
   System.out.println("------------------");
   System.out.println(response.getStatusLine());
   LinkFilter filter =
       new LinkFilter() {
         @Override
         public boolean accept(String url) {
           if (url.startsWith("http://www.wandoujia.com")) {
             return true;
           } else {
             return false;
           }
         }
       };
   Set<String> urls =
       HtmlParserTool.extractLinks(EntityUtils.toString(response.getEntity()), filter);
   for (String str : urls) {
     System.out.println(str);
   }
   response.close();
   client.close();
 }
Esempio n. 5
0
  @Test
  public void testUpdateWithTagWithSchemeAndLabel() throws Exception {

    DiagnosticReport dr = new DiagnosticReport();
    dr.setId("001");
    dr.addCodedDiagnosis().addCoding().setCode("AAA");

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001");
    httpPost.addHeader("Category", "Dog; scheme=\"http://foo\"; label=\"aaaa\"");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(dr),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));
    CloseableHttpResponse status = ourClient.execute(httpPost);
    assertEquals(1, ourReportProvider.getLastTags().size());
    assertEquals(new Tag("http://foo", "Dog", "aaaa"), ourReportProvider.getLastTags().get(0));
    IOUtils.closeQuietly(status.getEntity().getContent());

    httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001");
    httpPost.addHeader("Category", "Dog; scheme=\"http://foo\"; label=\"aaaa\";   ");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(dr),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));
    status = ourClient.execute(httpPost);
    IOUtils.closeQuietly(status.getEntity().getContent());

    assertEquals(1, ourReportProvider.getLastTags().size());
    assertEquals(new Tag("http://foo", "Dog", "aaaa"), ourReportProvider.getLastTags().get(0));
  }
  @Test
  public void testSearchIncludesParametersNone() throws Exception {
    HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=searchIncludes");

    CloseableHttpResponse status = ourClient.execute(httpGet);
    IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    assertEquals(200, status.getStatusLine().getStatusCode());

    assertThat(ourLastIncludes, empty());
  }
 /**
  * Generic method to convert JSON to Postduif objects. It uses the InputStream from a HttpResponse
  * as input for Jackson.
  *
  * @param response The response
  * @param type Generic type
  * @return List of Objects
  */
 public List<N> createObjectsList(CloseableHttpResponse response, Class<N> type) {
   List<N> objectList = new ArrayList<N>();
   try {
     CollectionType collectionType =
         createObjectMapper().getTypeFactory().constructCollectionType(List.class, type);
     objectList =
         createObjectMapper().readValue(response.getEntity().getContent(), collectionType);
     response.getEntity().getContent().close();
   } catch (IOException e) {
     LOGGER.error("IOException, message: " + e.getLocalizedMessage());
   }
   return objectList;
 }
  /** Try loading the page as a POST just to make sure we get the right error */
  @Test
  public void testGetPagesWithPost() throws Exception {

    HttpPost httpPost = new HttpPost("http://localhost:" + ourPort);
    List<? extends NameValuePair> parameters =
        Collections.singletonList(new BasicNameValuePair("_getpages", "AAA"));
    httpPost.setEntity(new UrlEncodedFormEntity(parameters));

    CloseableHttpResponse status = ourClient.execute(httpPost);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    ourLog.info(responseContent);
    assertEquals(400, status.getStatusLine().getStatusCode());
    assertThat(responseContent, containsString("Requests for _getpages must use HTTP GET"));
  }
Esempio n. 9
0
  /**
   * @param uri
   * @return
   */
  public static String getResponseBody(String uri) {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    try {
      HttpGet httpGet = new HttpGet(uri);
      CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

      try {
        HttpEntity httpEntity = httpResponse.getEntity();
        return EntityUtils.toString(httpEntity);
      } finally {
        if (httpResponse != null) {
          httpResponse.close();
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (httpClient != null) {
        try {
          httpClient.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    return null;
  }
Esempio n. 10
0
  public static void downloadPageByGetMethod(String url, String[] arg) throws IOException {

    // 1、�?过HttpGet获取到response对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 注意,必�?��加上http://的前�?��否则会报:Target host is null异常�?
    HttpGet httpGet = new HttpGet(url);
    CloseableHttpResponse response = httpClient.execute(httpGet);

    InputStream is = null;
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      try {
        // 2、获取response的entity�?
        HttpEntity entity = response.getEntity();

        // 3、获取到InputStream对象,并对内容进行处�?
        is = entity.getContent();

        String fileName = getFileName(arg);

        saveToFile(saveUrl, fileName, is);
      } catch (ClientProtocolException e) {
        e.printStackTrace();
      } finally {

        if (is != null) {
          is.close();
        }
        if (response != null) {
          response.close();
        }
      }
    }
  }
Esempio n. 11
0
  /**
   * Sends a GET request and returns the response.
   *
   * @param endpoint The endpoint to send the request to.
   * @param headers Any additional headers to send with this request. You can use {@link
   *     org.apache.http.HttpHeaders} constants for header names.
   * @return A {@link Path} to the downloaded content, if any.
   * @throws IOException If an error occurs.
   * @see java.nio.file.Files#probeContentType(Path)
   */
  public Response<Path> get(Endpoint endpoint, NameValuePair... headers) throws IOException {

    // Create the request
    HttpGet get = new HttpGet(endpoint.url());
    get.setHeaders(combineHeaders(headers));
    Path tempFile = null;

    // Send the request and process the response
    try (CloseableHttpResponse response = httpClient().execute(get)) {

      if (response.getStatusLine().getStatusCode() != HttpStatus.OK_200) {
        return null;
      } // If bad response return null

      // Request the content
      HttpEntity entity = response.getEntity();

      // Download the content to a temporary file
      if (entity != null) {
        tempFile = Files.createTempFile("download", "file");
        try (InputStream input = entity.getContent();
            OutputStream output = Files.newOutputStream(tempFile)) {
          IOUtils.copy(input, output);
        }
      }

      return new Response<>(response.getStatusLine(), tempFile);
    }
  }
 private boolean isClassAvailableToDeployment(String deploymentName, Class<?> clazz)
     throws IOException, HttpException {
   String className = clazz.getName();
   String CONTEXT_URL = PortProviderUtil.generateURL("/", deploymentName);
   HttpGet httpget =
       new HttpGet(
           CONTEXT_URL
               + TestResource.LOAD_CLASS_PATH
               + "?"
               + TestResource.CLASSNAME_PARAM
               + "="
               + className);
   try {
     String responseString = new String();
     HttpClientContext context = HttpClientContext.create();
     CloseableHttpResponse response = client.execute(httpget, context);
     HttpEntity entity = response.getEntity();
     if (entity != null) {
       responseString = EntityUtils.toString(entity, StandardCharsets.UTF_8);
     }
     return (HttpStatus.SC_OK == response.getStatusLine().getStatusCode())
         && (className.equals(responseString));
   } finally {
     httpget.releaseConnection();
   }
 }
Esempio n. 13
0
  public void propfind(HttpPropfind.Mode mode)
      throws URISyntaxException, IOException, DavException, HttpException {
    @Cleanup CloseableHttpResponse response = null;

    // processMultiStatus() requires knowledge of the actual content location,
    // so we have to handle redirections manually and create a new request for the new location
    for (int i = context.getRequestConfig().getMaxRedirects(); i > 0; i--) {
      HttpPropfind propfind = new HttpPropfind(location, mode);
      response = httpClient.execute(propfind, context);

      if (response.getStatusLine().getStatusCode() / 100 == 3) {
        location = DavRedirectStrategy.getLocation(propfind, response, context);
        Log.i(TAG, "Redirection on PROPFIND; trying again at new content URL: " + location);
        // don't forget to throw away the unneeded response content
        HttpEntity entity = response.getEntity();
        if (entity != null) {
          @Cleanup InputStream content = entity.getContent();
        }
      } else break; // answer was NOT a redirection, continue
    }
    if (response == null) throw new DavNoContentException();

    checkResponse(response); // will also handle Content-Location
    processMultiStatus(response);
  }
Esempio n. 14
0
  // 底层请求打印页面
  private byte[] sendRequest(HttpRequestBase request) throws Exception {
    CloseableHttpResponse response = httpclient.execute(request);

    // 设置超时
    setTimeOut(request, 5000);

    // 获取返回的状态列表
    StatusLine statusLine = response.getStatusLine();
    System.out.println("StatusLine : " + statusLine);

    if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
      try {
        // 获取response entity
        HttpEntity entity = response.getEntity();
        System.out.println("getContentType : " + entity.getContentType().getValue());
        System.out.println("getContentEncoding : " + entity.getContentEncoding().getValue());

        // 读取响应内容
        byte[] responseBody = EntityUtils.toByteArray(entity);

        // 关闭响应流
        EntityUtils.consume(entity);
        return responseBody;
      } finally {
        response.close();
      }
    }
    return null;
  }
  protected String getRequest() throws Exception {
    String ret = "";

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(coreJobServerUrl + "/hoot-services/ingest/customscript/getlist");
    CloseableHttpResponse response = httpclient.execute(httpget);
    try {

      if (response.getStatusLine().getStatusCode() != 200) {
        String reason = response.getStatusLine().getReasonPhrase();
        if (reason == null) {
          reason = "Unkown reason.";
        }
        throw new Exception(reason);
      }

      HttpEntity entity = response.getEntity();
      if (entity != null) {
        long len = entity.getContentLength();
        ret = EntityUtils.toString(entity);
      }
    } finally {
      response.close();
    }

    return ret;
  }
  @Test
  public void shouldRespondWithLightblueServiceResponseBodyThenCloseResponse()
      throws IOException, ServletException {
    CloseableHttpClient mockHttpClient = mock(CloseableHttpClient.class);
    CloseableHttpResponse mockLightblueResponse = mock(CloseableHttpResponse.class);
    HttpEntity mockEntity = mock(HttpEntity.class);

    when(mockHttpClient.execute(any(HttpUriRequest.class))).thenReturn(mockLightblueResponse);
    when(mockLightblueResponse.getEntity()).thenReturn(mockEntity);

    AbstractLightblueProxyServlet servlet =
        getTestServlet(mockHttpClient, null, "http://myservice.com", null);

    HttpServletRequest stubRequest =
        new StubHttpServletRequest(
            "http://test.com/servlet/file", "GET", "{test:0}", "application/json", "/servlet/*");

    HttpServletResponse mockProxyResponse = mock(HttpServletResponse.class);
    ServletOutputStream outputStream = new FakeServletOutputStream(new ByteArrayOutputStream());
    when(mockProxyResponse.getOutputStream()).thenReturn(outputStream);

    servlet.service(stubRequest, mockProxyResponse);

    InOrder inOrder = inOrder(mockEntity, mockLightblueResponse);
    inOrder.verify(mockEntity).writeTo(outputStream);
    inOrder.verify(mockLightblueResponse).close();
  }
  @Test
  public void basicAuth() throws Exception {
    setupRealmUser();
    KerberosContainer kdc = startKdc();
    configureSso(kdc, true);

    // I am not able to get the basic auth to work in FF 45.3.0, so using HttpClient instead
    // org.openqa.selenium.UnsupportedCommandException: Unrecognized command: POST
    // /session/466a800f-eaf8-40cf-a9e8-815f5a6e3c32/alert/credentials
    // alert.setCredentials(new UserAndPassword("user", "ATH"));

    CloseableHttpClient httpClient = getBadassHttpClient();

    // No credentials provided
    assertUnauthenticatedRequestIsRejected(httpClient);

    // Correct credentials provided
    HttpGet get = new HttpGet(jenkins.url.toExternalForm() + "/whoAmI");
    get.setHeader("Authorization", "Basic " + Base64.encode("user:ATH".getBytes()));
    CloseableHttpResponse response = httpClient.execute(get);
    String phrase = response.getStatusLine().getReasonPhrase();
    String out = IOUtils.toString(response.getEntity().getContent());
    assertThat(phrase + ": " + out, out, containsString("Full Name"));
    assertThat(phrase + ": " + out, out, containsString("Granted Authorities: authenticated"));
    assertEquals(phrase + ": " + out, "OK", phrase);

    // Incorrect credentials provided
    get = new HttpGet(jenkins.url.toExternalForm() + "/whoAmI");
    get.setHeader("Authorization", "Basic " + Base64.encode("user:WRONG_PASSWD".getBytes()));
    response = httpClient.execute(get);
    assertEquals(
        "Invalid password/token for user: user", response.getStatusLine().getReasonPhrase());
  }
Esempio n. 18
0
  public static Object fetch(DocumentSource source) {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
      URIBuilder builder = new URIBuilder(source.url);
      for (Entry<String, String> it : source.parameters.entrySet()) {
        builder.addParameter(it.getKey(), it.getValue());
      }
      URI uri = builder.build();

      HttpUriRequest request = new HttpGet(uri);
      request.addHeader("Accept", "application/json");
      CloseableHttpResponse response = httpclient.execute(request);

      String headers = response.getFirstHeader("Content-Type").getValue();
      InputStream inputStream = response.getEntity().getContent();
      if (headers.contains("text/html")) {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        Document document = Jsoup.parse(inputStream, null, source.url);
        return document;
      } else if (headers.contains("json")) {
        ObjectMapper om = new ObjectMapper();
        return om.readValue(inputStream, HashMap.class);
      } else {
        IOUtils.copy(inputStream, System.err);
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return null;
  }
  /**
   * 发送POST请求
   *
   * @param url 网络请求地址
   * @param nvps 请求参数列表
   * @return
   */
  public String post(String url, List<NameValuePair> nvps) {
    HttpPost request = new HttpPost(url);
    CloseableHttpResponse response = null;
    try {
      request.setEntity(new UrlEncodedFormEntity(nvps)); // 封装post请求参数
      response = client.execute(request); // 发送请求
      int resultCode = response.getStatusLine().getStatusCode(); // 返回响应状态

      /** ************** 网络异常, 退出程序 ************* */
      if (HttpStatus.SC_OK != resultCode) return EMPTY;

      /** ************** 将响应转换为字符串 ************* */
      HttpEntity entity = response.getEntity();
      return EntityUtils.toString(entity, UTF_8);
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (null != request && !request.isAborted()) {
        request.abort();
      }
      HttpClientUtils.closeQuietly(client);
      HttpClientUtils.closeQuietly(response);
    }
    return EMPTY;
  }
  @Test
  public void testPost() throws IOException {

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("extTID", "3"));
    formparams.add(new BasicNameValuePair("extAction", "exceptionFormPostController"));
    formparams.add(new BasicNameValuePair("extMethod", "throwAException"));
    formparams.add(new BasicNameValuePair("extType", "rpc"));
    formparams.add(new BasicNameValuePair("extUpload", "false"));

    UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formparams, "UTF-8");

    post.setEntity(postEntity);

    CloseableHttpResponse response = client.execute(post);
    HttpEntity entity = response.getEntity();
    assertThat(entity).isNotNull();
    String responseString = EntityUtils.toString(entity);
    ObjectMapper mapper = new ObjectMapper();

    Map<String, Object> rootAsMap = mapper.readValue(responseString, Map.class);
    assertThat(rootAsMap).hasSize(6);
    assertThat(rootAsMap.get("method")).isEqualTo("throwAException");
    assertThat(rootAsMap.get("type")).isEqualTo("exception");
    assertThat(rootAsMap.get("action")).isEqualTo("exceptionFormPostController");
    assertThat(rootAsMap.get("tid")).isEqualTo(3);
    assertThat(rootAsMap.get("message")).isEqualTo("a null pointer");
    assertThat(rootAsMap.get("where")).isNull();

    Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result");
    assertThat(result).hasSize(1);
    assertThat((Boolean) result.get("success")).isFalse();
    IOUtils.closeQuietly(response);
  }
Esempio n. 21
0
  public void send(GCMMessage messageBase) throws Exception {
    if (gcmURI == null) {
      throw new Exception("Error sending push. Google cloud messaging properties not provided.");
    }

    HttpPost httpPost = new HttpPost(gcmURI);
    httpPost.setHeader("Authorization", API_KEY);
    httpPost.setEntity(new StringEntity(messageBase.toJson(), ContentType.APPLICATION_JSON));

    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
      HttpEntity entity = response.getEntity();
      String responseMsg = EntityUtils.toString(entity);
      if (response.getStatusLine().getStatusCode() == 200) {
        GCMResponseMessage gcmResponseMessage = gcmResponseReader.readValue(responseMsg);
        if (gcmResponseMessage.failure == 1) {
          if (gcmResponseMessage.results != null && gcmResponseMessage.results.length > 0) {
            throw new Exception(
                "Error sending push. Problem : " + gcmResponseMessage.results[0].error);
          } else {
            throw new Exception("Error sending push. Token : " + messageBase.getToken());
          }
        }
      } else {
        EntityUtils.consume(entity);
        throw new Exception(responseMsg);
      }
    } finally {
      httpPost.releaseConnection();
    }
  }
  /** {@inheritDoc} */
  @Override
  public ClientResponse apply(ClientRequest jerseyRequest) {
    try {
      final HttpUriRequest apacheRequest = buildApacheRequest(jerseyRequest);
      final CloseableHttpResponse apacheResponse = client.execute(apacheRequest);

      final StatusLine statusLine = apacheResponse.getStatusLine();
      final Response.StatusType status =
          Statuses.from(statusLine.getStatusCode(), firstNonNull(statusLine.getReasonPhrase(), ""));

      final ClientResponse jerseyResponse = new ClientResponse(status, jerseyRequest);
      for (Header header : apacheResponse.getAllHeaders()) {
        final List<String> headerValues = jerseyResponse.getHeaders().get(header.getName());
        if (headerValues == null) {
          jerseyResponse.getHeaders().put(header.getName(), Lists.newArrayList(header.getValue()));
        } else {
          headerValues.add(header.getValue());
        }
      }

      final HttpEntity httpEntity = apacheResponse.getEntity();
      jerseyResponse.setEntityStream(
          httpEntity != null ? httpEntity.getContent() : new ByteArrayInputStream(new byte[0]));

      return jerseyResponse;
    } catch (Exception e) {
      throw new ProcessingException(e);
    }
  }
  @Test
  public void testKeepAlive() throws Exception {
    String url = httpServerUrl + "4ae3851817194e2596cf1b7103603ef8/pin/a14";

    HttpPut request = new HttpPut(url);
    request.setHeader("Connection", "keep-alive");

    HttpGet getRequest = new HttpGet(url);
    getRequest.setHeader("Connection", "keep-alive");

    for (int i = 0; i < 100; i++) {
      request.setEntity(new StringEntity("[\"" + i + "\"]", ContentType.APPLICATION_JSON));

      try (CloseableHttpResponse response = httpclient.execute(request)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        EntityUtils.consume(response.getEntity());
      }

      try (CloseableHttpResponse response2 = httpclient.execute(getRequest)) {
        assertEquals(200, response2.getStatusLine().getStatusCode());
        List<String> values = consumeJsonPinValues(response2);
        assertEquals(1, values.size());
        assertEquals(String.valueOf(i), values.get(0));
      }
    }
  }
 /**
  * Retrieves the recorded prepared statement preparations. Note this the prepare calls your
  * applications makes, not the executions.
  *
  * @return PreparedStatementPreparation
  */
 public List<PreparedStatementPreparation> retrievePreparedStatementPreparations() {
   HttpGet get = new HttpGet(preparedStatementPreparationUrl);
   try {
     CloseableHttpResponse response = httpClient.execute(get);
     String body = EntityUtils.toString(response.getEntity());
     LOGGER.debug("Received response {}", body);
     int statusCode = response.getStatusLine().getStatusCode();
     if (statusCode != 200) {
       String errorMessage =
           String.format(
               "Non 200 status code when retrieving prepared statement preparations %s",
               statusCode);
       LOGGER.info(errorMessage);
       throw new ActivityRequestFailed(errorMessage);
     }
     PreparedStatementPreparation[] preparations =
         (PreparedStatementPreparation[])
             gson.fromJson(body, (Class) PreparedStatementPreparation[].class);
     LOGGER.debug("Parsed prepared statement preparations {}", Arrays.toString(preparations));
     return Arrays.asList(preparations);
   } catch (IOException e) {
     LOGGER.info(REQUEST_FAILED, e);
     throw new ActivityRequestFailed(REQUEST_FAILED, e);
   }
 }
Esempio n. 25
0
 @Override
 public boolean load(BuildCacheKey key, BuildCacheEntryReader reader) throws BuildCacheException {
   final URI uri = root.resolve("./" + key.getHashCode());
   HttpGet httpGet = new HttpGet(uri);
   CloseableHttpResponse response = null;
   try {
     response = httpClient.execute(httpGet);
     StatusLine statusLine = response.getStatusLine();
     if (LOGGER.isDebugEnabled()) {
       LOGGER.debug("Response for GET {}: {}", uri, statusLine);
     }
     int statusCode = statusLine.getStatusCode();
     if (statusCode >= 200 && statusCode < 300) {
       reader.readFrom(response.getEntity().getContent());
       return true;
     } else if (statusCode == 404) {
       return false;
     } else {
       throw new BuildCacheException(
           String.format(
               "HTTP cache returned status %d: %s for key '%s' from %s",
               statusCode, statusLine.getReasonPhrase(), key, getDescription()));
     }
   } catch (IOException e) {
     throw new BuildCacheException(
         String.format("loading key '%s' from %s", key, getDescription()), e);
   } finally {
     HttpClientUtils.closeQuietly(response);
   }
 }
Esempio n. 26
0
 public void download() {
   InputStream in = null;
   CloseableHttpResponse res = null;
   while (true) {
     try {
       Center center = p.next();
       File file = new File(path + "\\" + center.getX() + "_" + center.getY() + ".png");
       file.createNewFile();
       HttpGet get = new HttpGet(centerToURL(center));
       System.out.println(get.getURI().toString());
       res = client.execute(get);
       in = res.getEntity().getContent();
       BufferedImage image = ImageIO.read(in);
       WriteImage(image, file);
     } catch (Exception e) {
       e.printStackTrace();
       break;
     } finally {
       try {
         in.close();
         res.close();
       } catch (Exception e) {
         e.printStackTrace();
       }
     }
     try {
       savePictureInfo();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
Esempio n. 27
0
  /**
   * * Recreates POST from web interface, sends it to yodaQA and gets response
   *
   * @param address Address of yodaQA
   * @param request POST from web interface containing question
   * @param concepts More concepts to send to yodaQA
   * @return response of yodaQA
   */
  public String getPOSTResponse(
      String address,
      Request request,
      String question,
      ArrayDeque<Concept> concepts,
      String artificialClue) {
    String result = "";
    try {
      CloseableHttpClient httpClient = HttpClients.createDefault();
      HttpPost httpPost = new HttpPost(address);
      PostRecreator postRecreator = new PostRecreator();
      httpPost = postRecreator.recreatePost(httpPost, request, question, concepts, artificialClue);

      CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

      BufferedReader reader =
          new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));

      String inputLine;
      StringBuffer postResponse = new StringBuffer();

      while ((inputLine = reader.readLine()) != null) {
        postResponse.append(inputLine);
      }
      reader.close();
      httpClient.close();
      result = postResponse.toString();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
Esempio n. 28
0
  public static String sendGET(final String url)
      throws ClientProtocolException, IOException, HttpRequestFailureException {
    LOGGER.infof("Entering sendGET(%s)", url);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    // httpGet.addHeader("User-Agent", USER_AGENT);
    CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
    final int statusCode = httpResponse.getStatusLine().getStatusCode();
    if (statusCode != 200) {
      throw new HttpRequestFailureException(statusCode);
    }
    BufferedReader reader =
        new BufferedReader(
            new InputStreamReader(httpResponse.getEntity().getContent(), STREAM_CHARSET));

    String inputLine;
    StringBuffer response = new StringBuffer();
    final String lineSeparator = System.getProperty("line.separator");
    while ((inputLine = reader.readLine()) != null) {
      response.append(inputLine);
      response.append(lineSeparator);
    }
    reader.close();
    httpClient.close();

    String result = response.toString();
    if (LOGGER.isTraceEnabled()) {
      LOGGER.tracef("Leaving sendGET(): %s", result);
    } else {
      LOGGER.info("Leaving sendGET()");
    }
    return result;
  }
  @Test
  public static void depositeDetailTest() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
      HttpPost post = new HttpPost("http://192.168.2.111:8578/service?channel=QueryNoticePage");
      List<NameValuePair> list = new ArrayList<NameValuePair>();
      list.add(new BasicNameValuePair("platformId", "82044"));
      list.add(new BasicNameValuePair("appKey", "1"));

      post.setEntity(new UrlEncodedFormEntity(list));
      CloseableHttpResponse response = httpclient.execute(post);

      try {
        System.out.println(response.getStatusLine());
        HttpEntity entity2 = response.getEntity();
        String entity = EntityUtils.toString(entity2);
        if (entity.contains("code\":\"0")) {
          System.out.println("Success!");
          System.out.println("response content:" + entity);
        } else {
          System.out.println("Failure!");
          System.out.println("response content:" + entity);
          AssertJUnit.fail(entity);
        }
      } finally {
        response.close();
      }
    } finally {
      httpclient.close();
    }
  }
Esempio n. 30
0
  public static String shortIt(String longUrl) {
    if (!longUrl.startsWith("http")) {
      longUrl = "http://" + longUrl;
    }
    CloseableHttpClient httpclient = HttpClients.custom().build(); // 可以帮助记录cookie
    String result = longUrl;
    String uri = "http://vwz.me/API.php?url=" + longUrl + "&callback=json";
    HttpGet get = new HttpGet(uri);
    try {
      CloseableHttpResponse execute = httpclient.execute(get);
      int statusCode = execute.getStatusLine().getStatusCode();
      switch (statusCode) {
        case 200:
          String html = IOUtils.toString(execute.getEntity().getContent(), "UTF-8");
          String json = html.substring(5, html.length() - 2);
          logger.info("json : {}", json);
          result = parseMsg(json);
          break;
        default:
          break;
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
    try {
      httpclient.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    logger.info("short {} to {}", longUrl, result);
    return result;
  }