org.apache.http.impl.client.HttpClients#createDefault()源码实例Demo

下面列出了org.apache.http.impl.client.HttpClients#createDefault() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: performance-tests   文件: JunitExistingRestTest.java
/**
 * This test sometimes failed due to GitHub rate limiting settings.
 * The failures should be captured in the reports(CSV and html).
 * This is knowing kept here to test the rate limiting and show
 * how a failed test can be tracked in the log/reports
 */
@Test
public void testGitHubGetApi() throws IOException, InterruptedException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet request = new HttpGet("https://api.github.com//users/octocat");

    // - - - - - - - - - - - - - - - - - - - - - - - - -
    // Add known delay to reflect "responseDelay" value
    // in the CSV report at least more than this number.
    // - - - - - - - - - - - - - - - - - - - - - - - - -
    Thread.sleep(1000);

    HttpResponse response = httpClient.execute(request);
    final String responseBodyActual = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
    System.out.println("### response: \n" + responseBodyActual);

    assertThat(response.getStatusLine().getStatusCode(), CoreMatchers.is(200));
    assertThat(responseBodyActual, CoreMatchers.containsString("\"login\":\"octocat\""));

}
 
源代码2 项目: dubbo-plus   文件: ClientInvoker.java
@Test
public void invokeSayHello(){
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://localhost:8080/net.dubboclub.restful.api.FirstRestfulService1/sayHello/1.0.1/all");
    Map<String,String> requestEntity = new HashMap<String,String>();
    requestEntity.put("arg1","Bieber");
    HttpEntity httpEntity = new ByteArrayEntity(JSON.toJSONBytes(requestEntity));
    httpPost.setEntity(httpEntity);
    try {
        CloseableHttpResponse response =  httpclient.execute(httpPost);
        System.out.println(response.getStatusLine());
        HttpEntity entity2 = response.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        System.out.println(EntityUtils.toString(entity2));
        response.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
@Test
public void getShouldReturnBadRequestWhenFileNotExists() throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    String encode = Base64.getUrlEncoder().encodeToString("/some/location/".getBytes(StandardCharsets.UTF_8));
    HttpGet httpGet = new HttpGet("/FileDownloadServlet/" + encode);

    CloseableHttpResponse execute = httpClient.execute(serverHost, httpGet);

    int statusCode = execute.getStatusLine().getStatusCode();
    assertThat(statusCode, is(HttpStatus.SC_BAD_REQUEST));

    //check error message is set
    try (
            InputStream content = execute.getEntity().getContent()) {
        String s = IOUtils.toString(content, StandardCharsets.UTF_8);
        assertThat(s, is("Requested file doesn't exist."));
    }
}
 
源代码4 项目: incubator-gobblin   文件: EventhubDataWriter.java
/** User needs to provide eventhub properties */
public EventhubDataWriter(Properties properties) {
  PasswordManager manager = PasswordManager.getInstance(properties);

  namespaceName = properties.getProperty(BatchedEventhubDataWriter.EVH_NAMESPACE);
  eventHubName =  properties.getProperty(BatchedEventhubDataWriter.EVH_HUBNAME);
  sasKeyName = properties.getProperty(BatchedEventhubDataWriter.EVH_SAS_KEYNAME);
  String encodedSasKey = properties.getProperty(BatchedEventhubDataWriter.EVH_SAS_KEYVALUE);
  sasKey = manager.readPassword(encodedSasKey);
  targetURI = "https://" + namespaceName + ".servicebus.windows.net/" + eventHubName + "/messages";
  httpclient = HttpClients.createDefault();
  metricContext = Instrumented.getMetricContext(new State(properties),EventhubDataWriter.class);
  recordsAttempted = this.metricContext.meter(EventhubMetricNames.EventhubDataWriterMetrics.RECORDS_ATTEMPTED_METER);
  recordsSuccess = this.metricContext.meter(EventhubMetricNames.EventhubDataWriterMetrics.RECORDS_SUCCESS_METER);
  recordsFailed = this.metricContext.meter(EventhubMetricNames.EventhubDataWriterMetrics.RECORDS_FAILED_METER);
  bytesWritten = this.metricContext.meter(EventhubMetricNames.EventhubDataWriterMetrics.BYTES_WRITTEN_METER);
  writeTimer = this.metricContext.timer(EventhubMetricNames.EventhubDataWriterMetrics.WRITE_TIMER);
}
 
源代码5 项目: streams   文件: SimpleHTTPGetProcessor.java
@Override
public void prepare(Object configurationObject) {

  mapper = StreamsJacksonMapper.getInstance();

  uriBuilder = new URIBuilder()
      .setScheme(this.configuration.getProtocol())
      .setHost(this.configuration.getHostname())
      .setPath(this.configuration.getResourcePath());

  if (StringUtils.isNotBlank(configuration.getAccessToken()) ) {
    uriBuilder = uriBuilder.addParameter("access_token", configuration.getAccessToken());
  }
  if (StringUtils.isNotBlank(configuration.getUsername())
       &&
      StringUtils.isNotBlank(configuration.getPassword())) {
    String string = configuration.getUsername() + ":" + configuration.getPassword();
    authHeader = Base64.encodeBase64String(string.getBytes());
  }
  httpclient = HttpClients.createDefault();
}
 
源代码6 项目: incubator-gobblin   文件: AdminWebServerTest.java
@Test
public void testGetSettingsJs() throws IOException {
  CloseableHttpClient client = HttpClients.createDefault();
  HttpGet getReq = new HttpGet(String.format("http://localhost:%s/js/settings.js", this.portNumber));

  try (CloseableHttpResponse response = client.execute(getReq)) {
    assertEquals(200, response.getStatusLine().getStatusCode());
    HttpEntity body = response.getEntity();
    String bodyString = EntityUtils.toString(body);
    assertStringContains("http://foobar", bodyString);
    assertStringContains("3333", bodyString);
  }
}
 
public CombinedTestClient(final String protocol) throws Exception {
    switch (protocol) {
        case HTTP:
            httpClient = HttpClients.createDefault();
            break;
        case HTTPS:
            httpClient = createSslHttpClient();
            secure = true;
            break;
        case WS:
            this.wsBuilder = TestClientFactory.build();
            break;
        case WSS:
            this.wsBuilder = TestClientFactory.build();
            secure = true;
            break;
        case WS_AND_HTTP:
            httpClient = HttpClients.createDefault();
            this.wsBuilder = TestClientFactory.build();
            break;
        case WSS_AND_HTTPS:
            httpClient = createSslHttpClient();
            secure = true;
            this.wsBuilder = TestClientFactory.build();
            break;
    }
}
 
源代码8 项目: JerryMouse   文件: TestHttpHandler.java
@Test
public void httpHandlerCanReturnRequestHeaderAndBody() throws IOException {
    int availablePort = NetUtils.getAvailablePort();

    HashMap<String, ServletWrapper> mapper = new HashMap<>();
    ServletWrapper empty = new ServletWrapper(
            "empty",
            "/",
            "xxx.xxxx.xxxxx.IndexServlet",
            0,
            RequestServlet.class,
            new RequestServlet()
    );
    mapper.put("/", empty);
    MultiReactor reactor = MultiReactor.newBuilder()
            .setPort(availablePort)
            .setHandlerClass(HttpHandler.class)
            .setServletContext(new ServletContext(null, null, mapper, null, "sample.jar"))
            .setSubReactorCount(3)
            .build();
    Thread reactorT = new Thread(reactor);
    reactorT.start();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet("http://localhost:" + availablePort);
    CloseableHttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    String responseStr = EntityUtils.toString(entity);
    String expect = "GET / HTTP/1.1\r\n" +
            "Host: localhost:9820\r\n" +
            "Connection: Keep-Alive\r\n" +
            "User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_232)\r\n" +
            "Accept-Encoding: gzip,deflate\r\n" +
            "\r\n";
    assertEquals(expect, responseStr);
}
 
源代码9 项目: IGUANA   文件: SPARQLWorker.java
@Override
public void executeQuery(String query, String queryID) {
	Instant start = Instant.now();

	try {
		String qEncoded = URLEncoder.encode(query);
		String addChar = "?";
		if (service.contains("?")) {
			addChar = "&";
		}
		String url = service + addChar + "query=" + qEncoded;
		HttpGet request = new HttpGet(url);
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOut.intValue())
				.setConnectTimeout(timeOut.intValue()).build();

		if(this.responseType != null)
			request.setHeader(HttpHeaders.ACCEPT, this.responseType);

		request.setConfig(requestConfig);
		CloseableHttpClient client = HttpClients.createDefault();
		CloseableHttpResponse response = client.execute(request);

		// method to process the result in background
		super.processHttpResponse(queryID, start, client, response);

	} catch (Exception e) {
		LOGGER.warn("Worker[{{}} : {{}}]: Could not execute the following query\n{{}}\n due to", this.workerType,
				this.workerID, query, e);
		super.addResults(new QueryExecutionStats(queryID, COMMON.QUERY_UNKNOWN_EXCEPTION, durationInMilliseconds(start, Instant.now())));
	}

}
 
private Boolean CheckDocServUrl(String url) {
    try {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet request = new HttpGet(url + "healthcheck");
        CloseableHttpResponse response = httpClient.execute(request);

        String content = IOUtils.toString(response.getEntity().getContent(), "utf-8").trim();
        if (content.equalsIgnoreCase("true"))
            return true;
    } catch (Exception e) {
        log.debug("/healthcheck error: " + e.getMessage());
    }

    return false;
}
 
源代码11 项目: tinkerpop   文件: GremlinServerHttpIntegrateTest.java
@Test
public void should200OnGETWithGremlinQueryStringArgumentWithBindingsAndFunction() throws Exception {
    final CloseableHttpClient httpclient = HttpClients.createDefault();
    final HttpGet httpget = new HttpGet(TestClientFactory.createURLString("?gremlin=addItUp(Integer.parseInt(x),Integer.parseInt(y))&bindings.x=10&bindings.y=10"));

    try (final CloseableHttpResponse response = httpclient.execute(httpget)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("application/json", response.getEntity().getContentType().getValue());
        final String json = EntityUtils.toString(response.getEntity());
        final JsonNode node = mapper.readTree(json);
        assertEquals(20, node.get("result").get("data").get(GraphSONTokens.VALUEPROP).get(0).get(GraphSONTokens.VALUEPROP).intValue());
    }
}
 
源代码12 项目: java-docs-samples   文件: FhirResourceGet.java
public static void fhirResourceGet(String resourceName) throws IOException, URISyntaxException {
  // String resourceName =
  //    String.format(
  //        FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "resource-type",
  //  "resource-id");

  // Initialize the client, which will be used to interact with the service.
  CloudHealthcare client = createClient();
  HttpClient httpClient = HttpClients.createDefault();
  String uri = String.format("%sv1/%s", client.getRootUrl(), resourceName);
  URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());

  HttpUriRequest request = RequestBuilder.get().setUri(uriBuilder.build()).build();

  // Execute the request and process the results.
  HttpResponse response = httpClient.execute(request);
  HttpEntity responseEntity = response.getEntity();
  if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
    String errorMessage =
        String.format(
            "Exception retrieving FHIR resource: %s\n", response.getStatusLine().toString());
    System.err.print(errorMessage);
    responseEntity.writeTo(System.err);
    throw new RuntimeException(errorMessage);
  }
  System.out.println("FHIR resource retrieved: ");
  responseEntity.writeTo(System.out);
}
 
@Test(expected = IOException.class)
public void testDownloadSitemapError() throws Exception {
	CloseableHttpClient httpClient = null;
	try {
		httpClient = HttpClients.createDefault();
		sitemapCheckThread.downloadSitemap(httpClient, TEST_JETTY_HTTP + "sitemap.notexists.xml");
	} finally {
		if (httpClient != null) {
			httpClient.close();
		}
	}
}
 
源代码14 项目: mzmine2   文件: LibrarySubmitTask.java
/**
 * Submit json library entry to GNPS webserver
 * 
 * @param json
 */
private void submitGNPS(String json) {
  try {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
      MultipartEntity entity = new MultipartEntity();

      // ######################################################
      // NEEDED
      // user pass and json entry
      //
      entity.addPart("username", new StringBody(USER));
      entity.addPart("password", new StringBody(PASS));
      entity.addPart("spectrum", new StringBody(json));
      // job description is not entry description
      entity.addPart("description", new StringBody(SOURCE_DESCRIPTION));

      HttpPost httppost = new HttpPost(GNPS_LIBRARY_SUBMIT_URL);
      httppost.setEntity(entity);

      log.info("Submitting GNPS library entry " + httppost.getRequestLine());
      CloseableHttpResponse response = httpclient.execute(httppost);
      try {
        writeResults("GNPS submit entry response status: " + response.getStatusLine(),
            Result.INFO);
        log.info("GNPS submit entry response status: " + response.getStatusLine());
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
          log.info("GNPS submit entry response content length: " + resEntity.getContentLength());
          writeResults(
              "GNPS submit entry response content length: " + resEntity.getContentLength(),
              Result.SUCCED);

          String body = IOUtils.toString(resEntity.getContent());
          String url = "https://gnps.ucsd.edu/ProteoSAFe/status.jsp?task=" + body;
          log.log(Level.INFO, "Submission task: " + url);
          writeResults(url, Result.SUCCED, true);
          EntityUtils.consume(resEntity);
        } else {
          log.warning("Not submitted to GNPS:\n" + json);
          writeResults("Not submitted to GNPS\n" + json, Result.ERROR);
        }
      } finally {
        response.close();
      }
    } finally {
      httpclient.close();
    }
  } catch (IOException e) {
    log.log(Level.SEVERE, "Error while submitting GNPS job", e);
    throw new MSDKRuntimeException(e);
  }
}
 
public SlackNotificationImpl(String channel) {
    this.channel = channel;
    this.client = HttpClients.createDefault();
    this.params = new ArrayList<NameValuePair>();
}
 
源代码16 项目: iot-device-bosch-indego-controller   文件: App.java
public static void main (String[] args) throws ClientProtocolException, IOException,
        InterruptedException
{
    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(BASE_URL_PUSHWOOSH + "registerDevice");
    String jsonPost = ""//
            + "{" //
            + "  \"request\":{" //
            + "     \"application\":\"8FF60-0666B\"," //
            + "     \"push_token\":\"124692134091\"," //
            + "     \"hwid\":\"00-0C-29-E8-B1-8D\"," //
            + "     \"timezone\":3600," //
            + "     \"device_type\":3" //
            + "  }" //
            + "}";
    httpPost.setEntity(new StringEntity(jsonPost, ContentType.APPLICATION_JSON));
    CloseableHttpResponse response = httpClient.execute(httpPost);

    System.out.println(response.getStatusLine());
    Header[] headers = response.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        System.out.println(headers[i].getName() + ": " + headers[i].getValue());
    }
    HttpEntity entity = response.getEntity();
    String contents = EntityUtils.toString(entity);
    System.out.println(contents);

    Thread.sleep(5000);

    HttpPost httpGet = new HttpPost(BASE_URL_PUSHWOOSH + "checkMessage");
    String jsonGet = ""//
            + "{" //
            + "  \"request\":{" //
            + "     \"application\":\"8FF60-0666B\"," //
            + "     \"hwid\":\"00-0C-29-E8-B1-8D\"" //
            + "  }" //
            + "}";
    httpGet.setEntity(new StringEntity(jsonGet, ContentType.APPLICATION_JSON));
    httpClient.execute(httpGet);

    response.close();
}
 
源代码17 项目: wildfly-core   文件: CoreUtils.java
/**
 * Makes HTTP call with FORM authentication.
 *
 * @param URL
 * @param user
 * @param pass
 * @param expectedStatusCode
 * @throws Exception
 */
public static void makeCall(String URL, String user, String pass, int expectedStatusCode) throws Exception {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()){
        HttpGet httpget = new HttpGet(URL);

        HttpResponse response = httpclient.execute(httpget);

        HttpEntity entity = response.getEntity();
        if (entity != null) { EntityUtils.consume(entity); }

        // We should get the Login Page
        StatusLine statusLine = response.getStatusLine();
        System.out.println("Login form get: " + statusLine);
        assertEquals(200, statusLine.getStatusCode());

        // We should now login with the user name and password
        HttpPost httpost = new HttpPost(URL + "/j_security_check");

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("j_username", user));
        nvps.add(new BasicNameValuePair("j_password", pass));

        httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

        response = httpclient.execute(httpost);
        entity = response.getEntity();
        if (entity != null) { EntityUtils.consume(entity); }

        statusLine = response.getStatusLine();

        // Post authentication - we have a 302
        assertEquals(302, statusLine.getStatusCode());
        Header locationHeader = response.getFirstHeader("Location");
        String location = locationHeader.getValue();

        HttpGet httpGet = new HttpGet(location);
        response = httpclient.execute(httpGet);

        entity = response.getEntity();
        if (entity != null) { EntityUtils.consume(entity); }

        // Either the authentication passed or failed based on the expected status code
        statusLine = response.getStatusLine();
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
    }
}
 
源代码18 项目: dhis2-core   文件: HttpUtils.java
/**
 * Method to make an HTTP POST call to a given URL with/without authentication.
 *
 */
public static DhisHttpResponse httpPOST( String requestURL, Object body, boolean authorize, String username, String password,
    String contentType, int timeout ) throws Exception
{
    CloseableHttpClient httpClient = HttpClients.createDefault();

    RequestConfig requestConfig = RequestConfig.custom()
        .setConnectTimeout( timeout )
        .setSocketTimeout( timeout )
        .build();

    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    DhisHttpResponse dhisHttpResponse;

    try
    {
        HttpPost httpPost = new HttpPost( requestURL );
        httpPost.setConfig( requestConfig );

        if ( body instanceof Map )
        {
            @SuppressWarnings( "unchecked" )
            Map<String, String> parameters = (Map<String, String>) body;
            for ( Map.Entry<String, String> parameter : parameters.entrySet() )
            {
                if ( parameter.getValue() != null )
                {
                    pairs.add( new BasicNameValuePair( parameter.getKey(), parameter.getValue() ) );
                }
            }
            httpPost.setEntity( new UrlEncodedFormEntity( pairs, "UTF-8" ) );
        }
        else if ( body instanceof String )
        {
            httpPost.setEntity( new StringEntity( (String) body ) );
        }

        if ( !StringUtils.isNotEmpty( contentType ) )
        {
            httpPost.setHeader( "Content-Type", contentType );
        }

        if ( authorize )
        {
            httpPost.setHeader( "Authorization", CodecUtils.getBasicAuthString( username, password ) );
        }

        HttpResponse response = httpClient.execute( httpPost );
        log.info( "Successfully got response from http POST." );
        dhisHttpResponse = processResponse( requestURL, username, response );
    }
    catch ( Exception e )
    {
        log.error( "Exception occurred in httpPOST call with username " + username, e );
        throw e;

    }
    finally
    {
        if ( httpClient != null )
        {
            httpClient.close();
        }
    }

    return dhisHttpResponse;
}
 
源代码19 项目: ats-framework   文件: AtsDbLoggerUtilities.java
/**
 * Attach a local file to the a testcase in the Test Explorer DB.
 * <br>The file must not be bigger than 10MB
 * 
 * @param testcaseId the testcase id to which the file will be attached
 * @param fileLocation the absolute path to the file
 * @param testExplorerContextName the name of the web application, e.g. "TestExplorer" or "TestExplorer-4.0.0" etc.
 * @param testExplorerPort the port of the web application, e.g. 8080
 * @return TRUE if the operation was successful and false if not. A warning will be logged on failure.
 */
@PublicAtsApi
public boolean attachFileToTestcase( int testcaseId,
                                     String fileLocation,
                                     String testExplorerContextName,
                                     int testExplorerPort ) {

    fileLocation = fileLocation.replace("\\", "/");
    currentErrMsgPrefix = ERR_MSG_PREFIX.replace("{FILE}", fileLocation).replace("{testcaseID}", testcaseId + "");

    if (!checkFileExist(fileLocation)) {
        return false;
    }
    if (!checkFileSizeIsNotTooLarge(fileLocation)) {
        return false;
    }

    ActiveDbAppender dbAppender = ActiveDbAppender.getCurrentInstance();
    if (dbAppender == null) {
        logger.warn(currentErrMsgPrefix + ". Perhaps the database logging is turned off");
        return false;
    }

    final int runId = dbAppender.getRunId();
    final int suiteId = dbAppender.getSuiteId();

    /* Since the user provides testcase ID, we have to validate it - whether it refers to a testcase part of 
     * the current run and suite
     */
    if (runId < 1 || suiteId < 1 || testcaseId < 1) {
        logger.warn(currentErrMsgPrefix + ". Perhaps the database logging is turned off or you are trying to "
                    + "log while a testcase is not yet started");
        return false;
    }

    final String database = dbAppender.getDatabase();
    final String host = dbAppender.getHost();
    final String URL = "http://" + host + ":" + testExplorerPort + "/" + testExplorerContextName
                       + "/AttachmentsServlet";

    URL url = null;
    try {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        url = post.getURI().toURL();

        if (!isURLConnetionAvailable(url)) {
            return false;
        }
        logger.debug("POSTing " + fileLocation + " to " + URL);

        File file = new File(fileLocation);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, fileLocation);
        builder.addTextBody("dbName", database);
        builder.addTextBody("runId", Integer.toString(runId));
        builder.addTextBody("suiteId", Integer.toString(suiteId));
        builder.addTextBody("testcaseId", Integer.toString(testcaseId));

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        return checkPostExecutedSuccessfully(client.execute(post), fileLocation, testcaseId);
    } catch (FileNotFoundException fnfe) {
        logger.warn(currentErrMsgPrefix + ". It does not exist on the local file system", fnfe);
        return false;
    } catch (IOException ioe) {
        logger.warn(currentErrMsgPrefix + ". Upload to \"" + url + "\" failed", ioe);
        return false;
    }
}
 
源代码20 项目: v20-java   文件: Context.java
/**
 * Constructs the Context object.
 *
 * @param      uri    The uri
 * @param      token  The token
 * @deprecated Use ContextBuilder instead.
 */
@Deprecated
public Context(String uri, String token) {
    this(uri, token, "", AcceptDatetimeFormat.RFC3339, HttpClients.createDefault());
}