Example #1
0
  /**
   * Sends a single zip file
   *
   * @param zipFile Name of the zip file in the data directory.
   * @throws IOException
   */
  private void sendZipfile(String zipFile) throws IOException {
    logger.debug("Sending {}", zipFile);
    HttpPost post = new HttpPost(m_remoteUrl + "/api/v1/datapoints");

    File zipFileObj = new File(m_dataDirectory, zipFile);
    FileInputStream zipStream = new FileInputStream(zipFileObj);
    post.setHeader("Content-Type", "application/gzip");

    post.setEntity(new InputStreamEntity(zipStream, zipFileObj.length()));
    try (CloseableHttpResponse response = m_client.execute(post)) {

      zipStream.close();
      if (response.getStatusLine().getStatusCode() == 204) {
        zipFileObj.delete();
      } else {
        ByteArrayOutputStream body = new ByteArrayOutputStream();
        response.getEntity().writeTo(body);
        logger.error(
            "Unable to send file "
                + zipFile
                + ": "
                + response.getStatusLine()
                + " - "
                + body.toString("UTF-8"));
      }
    }
  }
  @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 #3
0
  @Override
  public boolean isValidEndPoint(final URL url) {
    Assert.notNull(this.httpClient);

    HttpEntity entity = null;

    try (CloseableHttpResponse response = this.httpClient.execute(new HttpGet(url.toURI()))) {
      final int responseCode = response.getStatusLine().getStatusCode();

      final int idx = Collections.binarySearch(this.acceptableCodes, responseCode);
      if (idx >= 0) {
        LOGGER.debug("Response code from server matched {}.", responseCode);
        return true;
      }

      LOGGER.debug(
          "Response code did not match any of the acceptable response codes. Code returned was {}",
          responseCode);

      if (responseCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
        final String value = response.getStatusLine().getReasonPhrase();
        LOGGER.error(
            "There was an error contacting the endpoint: {}; The error was:\n{}",
            url.toExternalForm(),
            value);
      }

      entity = response.getEntity();
    } catch (final Exception e) {
      LOGGER.error(e.getMessage(), e);
    } finally {
      EntityUtils.consumeQuietly(entity);
    }
    return false;
  }
  public void run() {

    try {

      //			System.out.println(Thread.currentThread().getName() + ": " + System.currentTimeMillis() +
      // ": " + "Connecting");
      log.writeLog(Thread.currentThread().getName() + ": " + "Connecting");

      CloseableHttpResponse response = client.execute(get);

      //			System.out.println(Thread.currentThread().getName() + ": " + System.currentTimeMillis() +
      // ": " + response.getStatusLine().getStatusCode() + " " +
      // response.getStatusLine().getReasonPhrase());
      log.writeLog(
          Thread.currentThread().getName()
              + ": "
              + response.getStatusLine().getStatusCode()
              + " "
              + response.getStatusLine().getReasonPhrase());
      response.close();

    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      //			System.out.println(Thread.currentThread().getName() + ": " + System.currentTimeMillis() +
      // ": " + "Connection timeout");
      identifier.updateMinMax(Integer.parseInt(Thread.currentThread().getName().split("-")[1]));
      log.writeLog(Thread.currentThread().getName() + ": " + "Connection timeout");
      //			e.printStackTrace();
    }
  }
Example #5
0
  /**
   * Sends a POST request with a file and returns the response.
   *
   * @param endpoint The endpoint to send the request to.
   * @param file The file to upload
   * @param responseClass The class to deserialise the Json response to. Can be null if no response
   *     message is expected.
   * @param <T> The type to deserialise the response to.
   * @return A {@link Response} containing the deserialised body, if any.
   * @throws IOException If an error occurs.
   * @see MultipartEntityBuilder
   */
  private <T> Response<T> post(Endpoint endpoint, File file, Class<T> responseClass)
      throws IOException {
    if (file == null) {
      return post(endpoint, responseClass);
    } // deal with null case

    // Create the request
    HttpPost post = new HttpPost(endpoint.url());
    post.setHeaders(combineHeaders());

    // Add fields as text pairs
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    // Add file as binary
    FileBody fileBody = new FileBody(file);
    multipartEntityBuilder.addPart("file", fileBody);

    // Set the body
    post.setEntity(multipartEntityBuilder.build());

    // Send the request and process the response
    try (CloseableHttpResponse response = httpClient().execute(post)) {
      if (String.class.isAssignableFrom(responseClass)) {
        String body = getResponseString(response);
        return new Response(response.getStatusLine(), body);
      } else {
        T body = deserialiseResponseMessage(response, responseClass);
        return new Response<>(response.getStatusLine(), body);
      }
    }
  }
Example #6
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);
    }
  }
  @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));
      }
    }
  }
Example #8
0
 public static HttpHeaderInfo getHttpHeader(String url, Map<Object, Object> headers)
     throws ClientProtocolException, IOException {
   HttpGet httpGet = new HttpGet(url);
   if (headers != null) {
     for (Map.Entry<Object, Object> entry : headers.entrySet()) {
       httpGet.addHeader(entry.getKey() + "", entry.getValue() + "");
     }
   }
   CloseableHttpResponse response = minHttpclient.execute(httpGet);
   try {
     response.close();
     HttpHeaderInfo headerInfo = new HttpHeaderInfo();
     headerInfo.setStatus(response.getStatusLine().getStatusCode());
     headerInfo.setReasonPhrase(response.getStatusLine().getReasonPhrase());
     Header[] allHeaders = response.getAllHeaders();
     if (allHeaders != null) {
       Map<String, Object> headerMap = new HashMap<String, Object>();
       for (Header header : allHeaders) {
         headerMap.put(header.getName(), header.getValue());
       }
       headerInfo.setHeaders(headerMap);
     }
     return headerInfo;
   } finally {
     response.close();
   }
 }
  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 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());
  }
Example #11
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);
    }
  }
Example #12
0
 public InputStream getInputStream() throws Exception {
   httpClient = HttpClients.createDefault();
   HttpGet httpGet = new HttpGet(uri);
   System.out.println(uri);
   RequestConfig requestConfig =
       RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
   httpGet.setConfig(requestConfig);
   // DefaultHttpRequestRetryHandler handler = new DefaultHttpRequestRetryHandler(3, false);
   // httpClient.setHttpRequestRetryHandler(handler);
   response = httpClient.execute(httpGet);
   System.out.println(response.getStatusLine());
   if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
     // System.out.println("Connect Error");
     return null;
   }
   if (key != null) {
     Header header = response.getFirstHeader(key);
     if (header == null) {
       // not valid date
       // System.out.println("Not valid date.");
       return null;
     }
   }
   entity = response.getEntity();
   return entity.getContent();
 }
  protected byte[] execute(HttpUriRequest request) throws IOException {
    Log.w(TAG, "connecting to " + apn.getMmsc());

    CloseableHttpClient client = null;
    CloseableHttpResponse response = null;
    try {
      client = constructHttpClient();
      response = client.execute(request);

      Log.w(TAG, "* response code: " + response.getStatusLine());

      if (response.getStatusLine().getStatusCode() == 200) {
        return parseResponse(response.getEntity().getContent());
      }
    } catch (NullPointerException npe) {
      // TODO determine root cause
      // see: https://github.com/WhisperSystems/Signal-Android/issues/4379
      throw new IOException(npe);
    } finally {
      if (response != null) response.close();
      if (client != null) client.close();
    }

    throw new IOException("unhandled response code");
  }
Example #14
0
 /**
  * Request.
  *
  * @param httpUriRequest the http uri request
  * @return the string
  */
 public static String request(HttpUriRequest httpUriRequest) {
   try (CloseableHttpResponse response = getHttpClient().execute(httpUriRequest)) {
     HttpEntity httpEntity = response.getEntity();
     int statusCode = response.getStatusLine().getStatusCode();
     if (statusCode >= 200 && statusCode < 300) return EntityUtils.toString(httpEntity);
     throw new IllegalStateException(
         response.getStatusLine().getStatusCode()
             + JMString.SPACE
             + response.getStatusLine().getReasonPhrase());
   } catch (IOException e) {
     throw JMExceptionManager.handleExceptionAndReturnRuntimeEx(log, e, "request", httpUriRequest);
   }
 }
  @Test
  public void testAuthentication() throws IOException, ScriptException {
    final TestHttpClient client = new TestHttpClient();
    try {

      HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/all-auth1");
      CloseableHttpResponse result = client.execute(get);
      Assert.assertEquals(StatusCodes.UNAUTHORIZED, result.getStatusLine().getStatusCode());
      Header[] values = result.getHeaders(WWW_AUTHENTICATE.toString());
      String header = getAuthHeader(BASIC, values);
      assertEquals(BASIC + " realm=\"Test Realm\"", header);
      HttpClientUtils.readResponse(result);

      get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/all-auth1");
      get.addHeader(
          AUTHORIZATION.toString(),
          BASIC + " " + FlexBase64.encodeString("user1:password1".getBytes(), false));
      result = client.execute(get);
      Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

      Assert.assertEquals("ok", HttpClientUtils.readResponse(result));

      get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/all-auth2");
      get.addHeader(
          AUTHORIZATION.toString(),
          BASIC + " " + FlexBase64.encodeString("user2:password2".getBytes(), false));
      result = client.execute(get);
      Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

      Assert.assertEquals("ok", HttpClientUtils.readResponse(result));

      get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/admin");
      get.addHeader(
          AUTHORIZATION.toString(),
          BASIC + " " + FlexBase64.encodeString("user1:password1".getBytes(), false));
      result = client.execute(get);
      Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

      Assert.assertEquals("ok", HttpClientUtils.readResponse(result));
      get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/admin");
      get.addHeader(
          AUTHORIZATION.toString(),
          BASIC + " " + FlexBase64.encodeString("user2:password2".getBytes(), false));
      result = client.execute(get);
      Assert.assertEquals(StatusCodes.FORBIDDEN, result.getStatusLine().getStatusCode());
      HttpClientUtils.readResponse(result);
    } finally {
      client.getConnectionManager().shutdown();
    }
  }
Example #16
0
  static void getAuthCode() {
    access_token = null;
    expires_in = -1;
    token_start_time = -1;
    refresh_token = null;
    new File("/home/sead/refresh.txt").delete();

    if (gProps == null) {
      initGProps();
    }

    // Contact google for a user code
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {

      String codeUri = gProps.auth_uri.substring(0, gProps.auth_uri.length() - 4) + "device/code";

      HttpPost codeRequest = new HttpPost(codeUri);

      MultipartEntityBuilder meb = MultipartEntityBuilder.create();
      meb.addTextBody("client_id", gProps.client_id);
      meb.addTextBody("scope", "email profile");
      HttpEntity reqEntity = meb.build();

      codeRequest.setEntity(reqEntity);
      CloseableHttpResponse response = httpclient.execute(codeRequest);
      try {

        if (response.getStatusLine().getStatusCode() == 200) {
          HttpEntity resEntity = response.getEntity();
          if (resEntity != null) {
            String responseJSON = EntityUtils.toString(resEntity);
            ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON);
            device_code = root.get("device_code").asText();
            user_code = root.get("user_code").asText();
            verification_url = root.get("verification_url").asText();
            expires_in = root.get("expires_in").asInt();
          }
        } else {
          log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase());
        }
      } finally {
        response.close();
        httpclient.close();
      }
    } catch (IOException e) {
      log.error("Error reading sead-google.json or making http requests for code.");
      log.error(e.getMessage());
    }
  }
Example #17
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);
  }
Example #18
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;
  }
Example #19
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;
  }
Example #20
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);
   }
 }
Example #21
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;
  }
 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();
   }
 }
Example #23
0
  /**
   * Sends a POST request with a file and returns the response.
   *
   * @param endpoint The endpoint to send the request to.
   * @param file The file to upload
   * @param responseClass The class to deserialise the Json response to. Can be null if no response
   *     message is expected.
   * @param fields Any name-value pairs to serialise
   * @param <T> The type to deserialise the response to.
   * @return A {@link Response} containing the deserialised body, if any.
   * @throws IOException If an error occurs.
   * @see MultipartEntityBuilder
   */
  public <T> Response<T> post(
      Endpoint endpoint, File file, Class<T> responseClass, NameValuePair... fields)
      throws IOException {
    if (file == null) {
      return post(endpoint, responseClass, fields);
    } // deal with null case

    // Create the request
    HttpPost post = new HttpPost(endpoint.url());
    post.setHeaders(combineHeaders());

    // Add fields as text pairs
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    for (NameValuePair field : fields) {
      multipartEntityBuilder.addTextBody(field.getName(), field.getValue());
    }
    // Add file as binary
    FileBody bin = new FileBody(file);
    multipartEntityBuilder.addPart("file", bin);

    // Set the body
    post.setEntity(multipartEntityBuilder.build());

    // Send the request and process the response
    try (CloseableHttpResponse response = httpClient().execute(post)) {
      T body = deserialiseResponseMessage(response, responseClass);
      return new Response<>(response.getStatusLine(), body);
    }
  }
Example #24
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});
  }
Example #25
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();
    }
  }
  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();
        }
      }
    }
  }
  @Test
  public void testRunReportsJobFailedForStaleResponse() throws Exception {
    final String identifier = "foo";
    final Header[] warning =
        new Header[] {
          new BasicHeader(HeaderConstants.WARNING, "110 localhost \"Response is stale\"")
        };

    final AsynchronousValidationRequest impl =
        new AsynchronousValidationRequest(
            mockParent,
            mockClient,
            route,
            request,
            context,
            mockExecAware,
            mockCacheEntry,
            identifier,
            0);

    when(mockClient.revalidateCacheEntry(route, request, context, mockExecAware, mockCacheEntry))
        .thenReturn(mockResponse);
    when(mockResponse.getStatusLine()).thenReturn(mockStatusLine);
    when(mockStatusLine.getStatusCode()).thenReturn(200);
    when(mockResponse.getHeaders(HeaderConstants.WARNING)).thenReturn(warning);

    impl.run();

    verify(mockClient).revalidateCacheEntry(route, request, context, mockExecAware, mockCacheEntry);
    verify(mockResponse).getStatusLine();
    verify(mockStatusLine).getStatusCode();
    verify(mockResponse).getHeaders(HeaderConstants.WARNING);
    verify(mockParent).markComplete(identifier);
    verify(mockParent).jobFailed(identifier);
  }
  @Test
  public void testRunCallsCachingClientAndRemovesIdentifier() throws Exception {
    final String identifier = "foo";

    final AsynchronousValidationRequest impl =
        new AsynchronousValidationRequest(
            mockParent,
            mockClient,
            route,
            request,
            context,
            mockExecAware,
            mockCacheEntry,
            identifier,
            0);

    when(mockClient.revalidateCacheEntry(route, request, context, mockExecAware, mockCacheEntry))
        .thenReturn(mockResponse);
    when(mockResponse.getStatusLine()).thenReturn(mockStatusLine);
    when(mockStatusLine.getStatusCode()).thenReturn(200);

    impl.run();

    verify(mockClient).revalidateCacheEntry(route, request, context, mockExecAware, mockCacheEntry);
    verify(mockResponse).getStatusLine();
    verify(mockParent).markComplete(identifier);
    verify(mockParent).jobSuccessful(identifier);
  }
  @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();
    }
  }
 private void assertUnauthenticatedRequestIsRejected(CloseableHttpClient httpClient)
     throws IOException {
   HttpGet get = new HttpGet(jenkins.url.toExternalForm());
   CloseableHttpResponse response = httpClient.execute(get);
   assertEquals("Unauthorized", response.getStatusLine().getReasonPhrase());
   assertEquals("Negotiate", response.getHeaders("WWW-Authenticate")[0].getValue());
 }