Example #1
0
  public static void main(String[] args) throws ClientProtocolException, IOException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

      // HttpClient httpClient = getTestHttpClient();
      // HttpHost proxy = new HttpHost("127.0.0.1", 8888);
      // httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
      // proxy);

      String apiKey = args[0];
      String latitude = "46.947922";
      String longitude = "7.444608";

      String urlTemplate = "https://api.forecast.io/forecast/%s/%s,%s";
      String url = String.format(urlTemplate, apiKey, latitude, longitude);
      System.out.println(url);

      HttpGet httpget = new HttpGet(url);
      try (CloseableHttpResponse response = httpClient.execute(httpget)) {
        System.out.println(response.getFirstHeader("Content-Encoding"));
        HeaderIterator it = response.headerIterator();
        while (it.hasNext()) {
          Object header = it.next();
          System.out.println(header);
        }

        HttpEntity entity = response.getEntity();
        String jsonData = EntityUtils.toString(entity, StandardCharsets.UTF_8);

        System.out.println(jsonData);
      }
    }
  }
Example #2
0
  public final void run() {
    proccess();

    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpPost httpPost =
        new HttpPost(
            "https://api.telegram.org/bot115447632:AAGiH7bX_7dpywsXWONvsJPESQe-N7EmcQI/sendMessage");
    httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
    httpPost.addHeader("charset", "UTF-8");
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("chat_id", String.valueOf(update.message.chat.id)));
    urlParameters.add(new BasicNameValuePair("text", mensagem));
    if (teclado != null) urlParameters.add(new BasicNameValuePair("reply_markup", teclado));
    if (mensagemRetornoID != null)
      urlParameters.add(
          new BasicNameValuePair("reply_to_message_id", mensagemRetornoID.toString()));

    try {
      httpPost.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));
      httpclient.execute(httpPost);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  @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();
    }
  }
Example #4
0
  public static String sendSSLPost(String url) throws ClientProtocolException, IOException {
    String line = null;
    StringBuilder stringBuilder = new StringBuilder();
    CloseableHttpClient httpClient = HttpClientUtil.createSSLClientDefault();
    HttpGet getdd = new HttpGet();
    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");

    // httpPost.setEntity(new StringEntity(JSON.toJSONString(param), "UTF-8"));

    HttpResponse response = httpClient.execute(httpPost);
    if (response.getStatusLine().getStatusCode() == 200) {

      org.apache.http.HttpEntity httpEntity = response.getEntity();

      if (httpEntity != null) {
        try {
          BufferedReader bufferedReader =
              new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8 * 1024);
          while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
          }

        } catch (Exception e) {

        }
      }
    }
    return stringBuilder.toString();
  }
  @Test
  public void multiple_headers_with_the_same_name_are_processed_successfully() throws Exception {

    final CloseableHttpClient client = mock(CloseableHttpClient.class);
    final DropwizardApacheConnector dropwizardApacheConnector =
        new DropwizardApacheConnector(client, null, false);
    final Header[] apacheHeaders = {
      new BasicHeader("Set-Cookie", "test1"), new BasicHeader("Set-Cookie", "test2")
    };

    final CloseableHttpResponse apacheResponse = mock(CloseableHttpResponse.class);
    when(apacheResponse.getStatusLine())
        .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK"));
    when(apacheResponse.getAllHeaders()).thenReturn(apacheHeaders);
    when(client.execute(Matchers.any())).thenReturn(apacheResponse);

    final ClientRequest jerseyRequest = mock(ClientRequest.class);
    when(jerseyRequest.getUri()).thenReturn(URI.create("http://localhost"));
    when(jerseyRequest.getMethod()).thenReturn("GET");
    when(jerseyRequest.getHeaders()).thenReturn(new MultivaluedHashMap<>());

    final ClientResponse jerseyResponse = dropwizardApacheConnector.apply(jerseyRequest);

    assertThat(jerseyResponse.getStatus())
        .isEqualTo(apacheResponse.getStatusLine().getStatusCode());
  }
  @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 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));
      }
    }
  }
  @Test
  public void testSingletonService(@ArquillianResource(MyServiceServlet.class) URL baseURL)
      throws IOException, URISyntaxException {

    // URLs look like "http://IP:PORT/singleton/service"
    URI defaultURI = MyServiceServlet.createURI(baseURL, MyServiceActivator.DEFAULT_SERVICE_NAME);
    URI quorumURI = MyServiceServlet.createURI(baseURL, MyServiceActivator.QUORUM_SERVICE_NAME);

    try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
      HttpResponse response = client.execute(new HttpGet(defaultURI));
      try {
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(NODE_1, response.getFirstHeader("node").getValue());
      } finally {
        HttpClientUtils.closeQuietly(response);
      }

      // Service should be started regardless of whether a quorum was required.
      response = client.execute(new HttpGet(quorumURI));
      try {
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(NODE_1, response.getFirstHeader("node").getValue());
      } finally {
        HttpClientUtils.closeQuietly(response);
      }
    }
  }
  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;
  }
Example #10
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;
  }
Example #11
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;
  }
  @Override
  public void run() {
    // TODO Auto-generated method stub
    CloseableHttpClient httpClient =
        (CloseableHttpClient) asyncContext.getRequest().getAttribute("httpClient");
    HttpGet get = new HttpGet(URL);
    @SuppressWarnings("unchecked")
    ResponseHandler<String> responseHandler =
        (ResponseHandler<String>) asyncContext.getRequest().getAttribute("responseHandler");
    String response = "";
    try {
      response = httpClient.execute(get, responseHandler);
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    String userID = asyncContext.getRequest().getParameter("userID");
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("response", response);
    params.put("patterns", patternMap);
    params.put("userID", userID);
    Transaction transaction = new GetUserBasicInfoTransaction();
    try {
      transaction.execute(params);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    asyncContext.complete();
  }
  @Test
  public void testTracingFalse()
      throws ClientProtocolException, IOException, UnsatisfiedExpectationException {
    when(clientTracer.startNewSpan(PATH)).thenReturn(null);

    final HttpRequestImpl request = new HttpRequestImpl();
    request
        .method(Method.GET)
        .path(PATH)
        .httpMessageHeader(BraveHttpHeaders.Sampled.getName(), "false");
    final HttpResponseImpl response = new HttpResponseImpl(200, null, null);
    responseProvider.set(request, response);

    final CloseableHttpClient httpclient =
        HttpClients.custom()
            .addInterceptorFirst(new BraveHttpRequestInterceptor(clientTracer))
            .addInterceptorFirst(new BraveHttpResponseInterceptor(clientTracer))
            .build();
    try {
      final HttpGet httpGet = new HttpGet(REQUEST);
      final CloseableHttpResponse httpClientResponse = httpclient.execute(httpGet);
      assertEquals(200, httpClientResponse.getStatusLine().getStatusCode());
      httpClientResponse.close();
      mockServer.verify();

      final InOrder inOrder = inOrder(clientTracer);
      inOrder.verify(clientTracer).startNewSpan(PATH);
      inOrder.verify(clientTracer).submitBinaryAnnotation("request", "GET " + PATH);
      inOrder.verify(clientTracer).setClientSent();
      inOrder.verify(clientTracer).setClientReceived();
      verifyNoMoreInteractions(clientTracer);
    } finally {
      httpclient.close();
    }
  }
Example #14
0
 /**
  * Pulls a page and attempts to discover a feed for it via link[rel='alternate'].
  *
  * @param url The URL of the page to try and discover the feed for.
  * @return The feedsource if matched or created, may be null.
  * @throws ClientProtocolException If the page could not be pulled.
  * @throws IOException If the page could not be pulled.
  * @throws DataOperationException If a query could not be executed.
  */
 public FeedSource discover(final String url)
     throws ClientProtocolException, IOException, DataOperationException {
   log.fine("Discovering feed for " + url);
   try (final CloseableHttpClient client = HttpClientBuilder.create().build()) {
     final HttpGet get = new HttpGet(url);
     try (final CloseableHttpResponse response = client.execute(get)) {
       final String html = EntityUtils.toString(response.getEntity());
       final Document doc = Jsoup.parse(html);
       final Elements alternateLinks = doc.select("link");
       for (final Element alternateLink : alternateLinks) {
         if ("alternate".equals(alternateLink.attr("rel"))) {
           if ("application/rss+xml".equals(alternateLink.attr("type"))) {
             log.fine("Found rss link " + alternateLink.attr("href"));
             final String rss = alternateLink.attr("href");
             return this.feedSourceManager.findOrCreateByFeedUrl(rss);
           }
           log.fine("Found alternate link " + alternateLink.html());
         } else {
           log.fine("Found link " + alternateLink.html());
         }
       }
     }
   }
   return null;
 }
  @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());
  }
Example #16
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;
  }
Example #17
0
  public static void createCreative(Creative creative) throws Exception {
    int status = 0;
    String jsonString = null;
    CloseableHttpClient client = HttpClientBuilder.create().build();

    HttpPost post = new HttpPost("https://rest.emaildirect.com/v1/Creatives?ApiKey=apikey");
    List<NameValuePair> params = creative.getParams();

    post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    HttpResponse response = client.execute(post);

    HttpEntity entity = response.getEntity();
    if (entity != null) {
      BufferedReader rd =
          new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

      try {
        jsonString = rd.lines().collect(Collectors.joining()).toString();
        System.out.println("JSON ->" + jsonString);
      } finally {
        rd.close();
      }
    }

    JSONObject jObj = new JSONObject(jsonString);

    if (status == 201) {
      creative.setCreativeID(jObj.getString("CreativeID"));
      creative.setCreativeTimestamp(jObj.getString("Created"));
      dbUpdate(creative);
    }
  }
  @Test
  public void testWaitForQuiescenceAfterRequestCompleted() throws IOException {
    mockServer
        .when(request().withMethod("GET").withPath("/quiescencecompleted"), Times.exactly(1))
        .respond(response().withStatusCode(200));

    try (CloseableHttpClient client = NewProxyServerTestUtil.getNewHttpClient(proxy.getPort())) {
      HttpResponse response =
          client.execute(
              new HttpGet("http://127.0.0.1:" + mockServerPort + "/quiescencecompleted"));
      EntityUtils.consumeQuietly(response.getEntity());

      assertEquals(
          "Expected successful response from server",
          200,
          response.getStatusLine().getStatusCode());
    }

    // wait for 2s of quiescence, now that the call has already completed
    long start = System.nanoTime();
    boolean waitSuccessful = proxy.waitForQuiescence(2, 5, TimeUnit.SECONDS);
    long finish = System.nanoTime();

    assertTrue("Expected to successfully wait for quiescence", waitSuccessful);

    assertTrue(
        "Expected to wait for quiescence for approximately 2s. Actual wait time was: "
            + TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS)
            + "ms",
        TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS) >= 1500
            && TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS) <= 2500);
  }
Example #19
0
  /**
   * Uploads a {@code File} with PRIVATE read access.
   *
   * @param uri upload {@link URI}
   * @param contentTypeString content type
   * @param contentFile the file to upload
   * @throws IOException
   */
  public static void uploadPrivateContent(
      final URI uri, final String contentTypeString, final File contentFile) throws IOException {

    LOGGER.info(
        "uploadPrivateContent START: uri: [{}]; content type: [{}], content file: [{}]",
        new Object[] {uri, contentTypeString, contentFile});

    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString);
    httpPut.addHeader(FileUtils.X_AMZ_ACL_HEADER_NAME, FileUtils.X_AMZ_ACL_HEADER_VALUE_PRIVATE);

    ContentType contentType = ContentType.create(contentTypeString);
    FileEntity fileEntity = new FileEntity(contentFile, contentType);
    httpPut.setEntity(fileEntity);

    CloseableHttpResponse response = closeableHttpClient.execute(httpPut);
    StatusLine statusLine = response.getStatusLine();

    if (!(statusLine.getStatusCode() == HttpStatus.SC_OK)) {
      throw new IOException(
          String.format(
              "An error occurred while trying to upload private file - %d: %s",
              statusLine.getStatusCode(), statusLine.getReasonPhrase()));
    }

    LOGGER.info(
        "uploadPrivateContent END: uri: [{}]; content type: [{}], content file: [{}]",
        new Object[] {uri, contentTypeString, contentFile});
  }
  @Test
  public void testWaitForQuiescenceQuietPeriodAlreadySatisfied()
      throws IOException, InterruptedException {
    mockServer
        .when(request().withMethod("GET").withPath("/quiescencesatisfied"), Times.exactly(1))
        .respond(response().withStatusCode(200));

    try (CloseableHttpClient client = NewProxyServerTestUtil.getNewHttpClient(proxy.getPort())) {
      HttpResponse response =
          client.execute(
              new HttpGet("http://127.0.0.1:" + mockServerPort + "/quiescencesatisfied"));
      EntityUtils.consumeQuietly(response.getEntity());

      assertEquals(
          "Expected successful response from server",
          200,
          response.getStatusLine().getStatusCode());
    }

    // wait for 2s, then wait for 1s of quiescence, which should already be satisfied
    Thread.sleep(2000);

    long start = System.nanoTime();
    boolean waitSuccessful = proxy.waitForQuiescence(1, 5, TimeUnit.SECONDS);
    long finish = System.nanoTime();

    assertTrue("Expected to successfully wait for quiescence", waitSuccessful);

    assertTrue(
        "Expected wait for quiescence to return immediately. Actual wait time was: "
            + TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS)
            + "ms",
        TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS) <= 1);
  }
  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;
  }
Example #22
0
  /** HttpClient 4.3 简单入门---HttpGet */
  @Test
  public void test01() {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // 创建httpClientBuilder
    CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); // 创建httpClient
    HttpGet httpGet = new HttpGet(HTTPGETTESTURL);
    logger.info("httpGet.getRequestLine():{}", httpGet.getRequestLine());

    try {
      HttpResponse httpResponse = closeableHttpClient.execute(httpGet); // 执行get请求
      HttpEntity httpEntity = httpResponse.getEntity(); // 获取响应消息实体
      logger.info("响应状态:{}", httpResponse.getStatusLine());
      if (httpEntity != null) {
        logger.info("contentEncoding:{}", httpEntity.getContentEncoding());
        logger.info("response content:{}", EntityUtils.toString(httpEntity));
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        closeableHttpClient.close(); // 关闭流并释放资源
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  @Test
  @OperateOnDeployment(DEPLOYMENT_1)
  public void testSerialized(@ArquillianResource(SimpleServlet.class) URL baseURL)
      throws IOException, URISyntaxException {

    // returns the URL of the deployment (http://127.0.0.1:8180/distributable)
    URI uri = SimpleServlet.createURI(baseURL);

    try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
      HttpResponse response = client.execute(new HttpGet(uri));
      try {
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue()));
        Assert.assertFalse(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
      } finally {
        HttpClientUtils.closeQuietly(response);
      }

      response = client.execute(new HttpGet(uri));
      try {
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue()));
        // This won't be true unless we have somewhere to which to replicate
        Assert.assertTrue(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
      } finally {
        HttpClientUtils.closeQuietly(response);
      }
    }
  }
Example #24
0
 /** HttpClient 4.3简单入门---HttpPost */
 @Test
 public void test02() {
   HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
   CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
   HttpPost httpPost = new HttpPost(HTTPPOSTTESTURL);
   //		httpPost.setConfig();
   List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 创建参数列表
   formParams.add(new BasicNameValuePair("type", "all"));
   formParams.add(new BasicNameValuePair("query", "httpClient"));
   formParams.add(new BasicNameValuePair("sort", ""));
   UrlEncodedFormEntity entity;
   try {
     entity = new UrlEncodedFormEntity(formParams, "UTF-8");
     httpPost.setEntity(entity);
     HttpResponse httpResponse = closeableHttpClient.execute(httpPost);
     HttpEntity httpEntity = httpResponse.getEntity();
     if (httpEntity != null) {
       logger.info("response:{}", EntityUtils.toString(httpEntity, "UTF-8"));
     }
     closeableHttpClient.close(); // 释放资源
   } catch (ClientProtocolException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Example #25
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;
  }
  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();
        }
      }
    }
  }
Example #27
0
  @RequestMapping(value = "/kkn1234/create", method = RequestMethod.POST)
  public String formSubmit(@ModelAttribute User user, Model model)
      throws MalformedURLException, IOException {
    model.addAttribute("user", user);
    HttpPost post =
        new HttpPost(
            "http://ec2-52-4-138-196.compute-1.amazonaws.com/magento/index.php/customer/account/createpost/");
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient =
        HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("firstname", user.getFirstName()));
    nameValuePairs.add(new BasicNameValuePair("lastname", user.getLastName()));
    nameValuePairs.add(new BasicNameValuePair("email", user.getEmail()));
    nameValuePairs.add(new BasicNameValuePair("password", user.getPassword()));
    nameValuePairs.add(new BasicNameValuePair("confirmation", user.getConfirmation()));

    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(post);
    response = httpclient.execute(post);
    System.out.println("Status code is " + response.getStatusLine().getStatusCode());
    System.out.println(response.toString());
    System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++");
    System.out.println(response.getFirstHeader("Location"));
    HttpEntity entity = response.getEntity();
    EntityUtils.consume(entity);
    EntityUtils.consume(response.getEntity());

    /*File newTextFile = new File("C:\\Users\\Kris\\Desktop\\temp.html");
    FileWriter fileWriter = new FileWriter(newTextFile);
    fileWriter.write(response.toString());
    fileWriter.close();*/
    return "result";
  }
Example #28
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));
  }
  public static String sendToRockBlockHttp(
      String destImei, String username, String password, byte[] data)
      throws HttpException, IOException {

    CloseableHttpClient client = HttpClientBuilder.create().build();

    HttpPost post = new HttpPost("https://secure.rock7mobile.com/rockblock/MT");
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("imei", destImei));
    urlParameters.add(new BasicNameValuePair("username", username));
    urlParameters.add(new BasicNameValuePair("password", password));
    urlParameters.add(new BasicNameValuePair("data", ByteUtil.encodeToHex(data)));

    post.setEntity(new UrlEncodedFormEntity(urlParameters));
    post.setHeader("Content-Type", "application/x-www-form-urlencoded");
    HttpResponse response = client.execute(post);

    BufferedReader rd =
        new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
      result.append(line);
    }

    try {
      client.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return result.toString();
  }
  public String invoke(Map<String, Object> paramter) throws Exception {

    Map<String, Object> result = null;

    String json = toJSON(paramter);
    String content = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(uri);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("arguJson", TripleDES.encryptString(json, key, iv)));
    String response = null;
    try {
      httpPost.setEntity(new UrlEncodedFormEntity(nvps));
      CloseableHttpResponse response2 = httpclient.execute(httpPost);
      HttpEntity entity2 = response2.getEntity();
      response = EntityUtils.toString(entity2);
      response = TripleDES.decryptString(response, key, iv);
      result = toMap(response);

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return JSON.toJSONString(result);
  }