Java Code Examples for org.apache.http.client.fluent.Request#Get

The following examples show how to use org.apache.http.client.fluent.Request#Get . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PriceLookup.java    From 07kit with GNU General Public License v3.0 6 votes vote down vote up
@Override
public PriceInfo load(String id) throws Exception {
	String path = id.startsWith("name-") ? "name/" : "id/";
	Request request = Request.Get(API_URL + path +
			(id.startsWith("name-") ?
			id.substring(id.indexOf('-') + 1)
			: id.replace("name-", "")));
	request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());

	HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();
	if (response != null) {
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			byte[] bytes = EntityUtils.toByteArray(response.getEntity());
			return GSON.fromJson(new String(bytes), PriceInfo.class);
		}
	}
	return null;
}
 
Example 2
Source File: PriceLookup.java    From 07kit with GNU General Public License v3.0 6 votes vote down vote up
public static List<PriceInfo> search(String term, int limit) {
	try {
		Request request = Request.Get(API_URL + "search?term=" + URLEncoder.encode(term, "UTF-8") + "&limit=" + limit);
		request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());

		HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();
		if (response != null) {
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				byte[] bytes = EntityUtils.toByteArray(response.getEntity());
				return GSON.fromJson(new String(bytes), PRICE_INFO_LIST_TYPE);
			}
		}
		return new ArrayList<>();
	} catch (IOException | CacheLoader.InvalidCacheLoadException e) {
		e.printStackTrace();
		return new ArrayList<>();
	}
}
 
Example 3
Source File: RoundRobinLoadBalancingSingleTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void call_round_robin_lb_single_endpoint() throws Exception {
    wireMockRule.stubFor(get("/api2").willReturn(ok()));

    Request request = Request.Get("http://localhost:8082/api");

    // Set the first endpoint with down status
    api.getProxy().getGroups().iterator().next().getEndpoints().iterator().next().setStatus(Endpoint.Status.DOWN);

    int calls = 20;

    for(int i = 0 ; i < calls ; i++) {
        HttpResponse response = request.execute().returnResponse();

        assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
    }

    wireMockRule.verify(0, getRequestedFor(urlPathEqualTo("/api1")));
    wireMockRule.verify(calls, getRequestedFor(urlPathEqualTo("/api2")));
}
 
Example 4
Source File: GenericBlockingRestKiqrClientImpl.java    From kiqr with Apache License 2.0 6 votes vote down vote up
private <U> U execute(URISupplier<URI> uriSupplier, MappingFunction<byte[], U> responseMapper, Supplier<U> notFoundMapper) {
    try {
        URI uri = uriSupplier.get();
        Request request = Request.Get(uri);
        HttpResponse response = request.execute().returnResponse();

        if (response.getStatusLine().getStatusCode() == 200) {
            byte[] returnJson = EntityUtils.toByteArray(response.getEntity());

            return responseMapper.apply(returnJson);


        } else if (response.getStatusLine().getStatusCode() == 404) {
            return notFoundMapper.get();
        } else if (response.getStatusLine().getStatusCode() == 400) {
            throw new IllegalArgumentException("Bad Request");
        } else {
            throw new QueryExecutionException("Something went wrong, status code: " + response.getStatusLine().getStatusCode());
        }


    } catch (URISyntaxException | IOException e) {
        throw new ConnectionException("Error creating connection", e);
    }

}
 
Example 5
Source File: InvalidHttpMethodGatewayTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRespondWithNotImplemented() throws Exception {
    wireMockRule.stubFor(any(urlEqualTo("/team/my_team"))
            .willReturn(aResponse().withStatus(HttpStatus.SC_NOT_IMPLEMENTED)));


    Request request = Request.Get("http://localhost:8082/test/my_team");

    // A little bit of reflection to set an unknown HTTP method since the fluent API does not allow it.
    Field requestField = request.getClass().getDeclaredField("request");
    requestField.setAccessible(true);
    Field methodField = requestField.get(request).getClass().getDeclaredField("method");
    methodField.setAccessible(true);
    methodField.set(requestField.get(request), "unkown-method");

    Response response = request.execute();
    HttpResponse returnResponse = response.returnResponse();

    assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, returnResponse.getStatusLine().getStatusCode());

    wireMockRule.verify(anyRequestedFor(urlPathEqualTo("/team/my_team")));
}
 
Example 6
Source File: WeightedRoundRobinLoadBalancingTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void call_weighted_lb_multiple_endpoints() throws Exception {
    wireMockRule.stubFor(get(urlEqualTo("/api1")).willReturn(ok()));
    wireMockRule.stubFor(get(urlEqualTo("/api2")).willReturn(ok()));

    Request request = Request.Get("http://localhost:8082/api");

    int calls = 10;

    for(int i = 0 ; i < calls ; i++) {
        Response response = request.execute();
        HttpResponse returnResponse = response.returnResponse();

        assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode());
    }

    wireMockRule.verify(3, getRequestedFor(urlPathEqualTo("/api1")));
    wireMockRule.verify(7, getRequestedFor(urlPathEqualTo("/api2")));
}
 
Example 7
Source File: RoundRobinLoadBalancingMultipleTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void call_round_robin_lb_multiple_endpoints() throws Exception {
    wireMockRule.stubFor(get("/api1").willReturn(ok()));
    wireMockRule.stubFor(get("/api2").willReturn(ok()));

    Request request = Request.Get("http://localhost:8082/api");

    int calls = 20;

    for(int i = 0 ; i < calls ; i++) {
        HttpResponse response = request.execute().returnResponse();

        assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
        wireMockRule.verify((i / 2) + 1, getRequestedFor(urlEqualTo("/api" + (i%2 + 1))));
    }

    wireMockRule.verify(calls / 2, getRequestedFor(urlPathEqualTo("/api1")));
    wireMockRule.verify(calls / 2, getRequestedFor(urlPathEqualTo("/api2")));
}
 
Example 8
Source File: HttpUtils.java    From sword-lang with Apache License 2.0 5 votes vote down vote up
/**
 * 下载文件
 * @param url   URL
 * @return      文件的二进制流,客户端使用outputStream输出为文件
 */
public static byte[] getFile(String url){
	try {
		Request request = Request.Get(url);
		HttpEntity resEntity = request.execute().returnResponse().getEntity();
		return EntityUtils.toByteArray(resEntity);
	} catch (Exception e) {
		logger.error("postFile请求异常," + e.getMessage() + "\n post url:" + url);
		e.printStackTrace();
	}
	return null;
}
 
Example 9
Source File: HttpFluentService.java    From AthenaServing with Apache License 2.0 5 votes vote down vote up
private String executeGet(String url, String hostName, Integer port, String schemeName, Map<String, String> paramMap) {
    Args.notNull(url, "url");

    url = buildGetParam(url, paramMap);
    Request request = Request.Get(url);
    request = buildProxy(request, hostName, port, schemeName);
    try {
        return request.execute().returnContent().asString(Consts.UTF_8);
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e.toString());
    }
    return null;
}
 
Example 10
Source File: DownloadStepdefs.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Request authenticatedDownloadRequest(URIBuilder uriBuilder, String blobId, String username) throws URISyntaxException {
    AccessToken accessToken = userStepdefs.authenticate(username);
    AttachmentAccessTokenKey key = new AttachmentAccessTokenKey(username, blobId);
    if (attachmentAccessTokens.containsKey(key)) {
        uriBuilder.addParameter("access_token", attachmentAccessTokens.get(key).serialize());
    }
    Request request = Request.Get(uriBuilder.build());
    if (accessToken != null) {
        request.addHeader("Authorization", accessToken.asString());
    }
    return request;
}
 
Example 11
Source File: UploadStepdefs.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Then("^\"([^\"]*)\" should be able to retrieve the content$")
public void contentShouldBeRetrievable(String username) throws Exception {
    AccessToken accessToken = userStepdefs.authenticate(username);
    DocumentContext jsonPath = JsonPath.parse(response.getEntity().getContent());
    Request request = Request.Get(baseUri(mainStepdefs.jmapServer).setPath("/download/" + jsonPath.<String>read("blobId")).build());
    if (accessToken != null) {
        request.addHeader("Authorization", accessToken.asString());
    }
    response = request.execute().returnResponse();
    httpAuthorizedStatus();
}
 
Example 12
Source File: UnfollowRedirectTest.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotFollowRedirect() throws Exception {
    wireMockRule.stubFor(get("/redirect").willReturn(permanentRedirect("http://localhost:" + wireMockRule.port() + "/final")));

    HttpClient client = HttpClientBuilder.create().disableRedirectHandling().build();

    Request request = Request.Get("http://localhost:8082/api/redirect");
    Response response = Executor.newInstance(client).execute(request);
    HttpResponse returnResponse = response.returnResponse();

    assertEquals(HttpStatus.SC_MOVED_PERMANENTLY, returnResponse.getStatusLine().getStatusCode());

    wireMockRule.verify(1, getRequestedFor(urlPathEqualTo("/redirect")));
    wireMockRule.verify(0, getRequestedFor(urlPathEqualTo("/final")));
}
 
Example 13
Source File: SecretsClient.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
/**
 * List all secrets paths for given path.
 *
 * @param path location to list
 * @return list of nested paths
 * @throws IOException if the list operation failed to complete
 */
public Collection<String> list(String path) throws IOException {
  Request httpRequest = Request.Get(uriForPath(String.format("%s?list=true", path)));
  String responseContent = new ContentResponseHandler()
      .handleEntity(query("list", path, httpRequest, HttpStatus.SC_OK).getEntity())
      .asString();
  JSONObject data = new JSONObject(responseContent);

  ArrayList<String> secrets = new ArrayList<>();
  data.getJSONArray("array")
      .iterator()
      .forEachRemaining(secret -> secrets.add((String) secret));

  return secrets;
}
 
Example 14
Source File: HttpClientWrapper.java    From adaptive-alerting with Apache License 2.0 5 votes vote down vote up
/**
 * Makes an HTTP GET call with headers to the given URI and returns the result.
 *
 * @param uri URI
 * @return Call result
 * @throws IOException if there's a problem making the call
 */
public Content get(String uri, Map<String, String> headers) throws IOException {
    if (headers.isEmpty()) {
        return get(uri);
    }
    val getRequest = Request.Get(uri);
    return buildRequestWithHeaders(getRequest, headers)
            .execute()
            .returnContent();
}
 
Example 15
Source File: TwitchChatPlugin.java    From 07kit with GNU General Public License v3.0 4 votes vote down vote up
private PircBotX createBot(int attempt) {
    try {
        lastOAuthToken = twitchOAuthToken;
        Request request = Request.Get(OAUTH_USER_INFO_URL + twitchOAuthToken.substring(twitchOAuthToken.contains(":") ?
                twitchOAuthToken.indexOf(':') + 1 : 0));

        HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();
        if (response != null) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                byte[] bytes = EntityUtils.toByteArray(response.getEntity());
                userInfo = GSON.fromJson(new String(bytes), TwitchUserInfo.class);
            }
        }

        if (userInfo != null && userInfo.isIdentified()) {
            String channelToJoin = "#" + userInfo.getToken().getUsername();
            Configuration configuration = new Configuration.Builder()
                    .setName(userInfo.getToken().getUsername())
                    .setServerPassword(twitchOAuthToken)
                    .addServer(IRC_HOST)
                    .addAutoJoinChannel(channelToJoin)
                    .addListener(new TwitchChatMessageHandler())
                    .buildConfiguration();

            PircBotX bot = new PircBotX(configuration);
            bot.startBot();
            logger.info("Connecting to Twitch Chat for " + userInfo.getToken().getUsername());
        } else {
            NotificationsUtil.showNotification("Error", "Unable to start Twitch Chat Client, OAuth Token is invalid.");
        }

    } catch (IOException | IrcException e) {//TODO report failure back to user better
        logger.error("Error starting up Twitch Chat Client", e);
        if (attempt < MAX_CONNECTION_ATTEMPTS) {
            NotificationsUtil.showNotification("Error", "Unable to start Twitch Chat Client, retrying...");
            int next = attempt + 1;
            return createBot(next);
        } else {
            NotificationsUtil.showNotification("Error", "Unable to start Twitch Chat Client, giving up.");
        }
    }

    return bot;
}
 
Example 16
Source File: DownloadStepdefs.java    From james-project with Apache License 2.0 4 votes vote down vote up
private Request queryParameterDownloadRequest(URIBuilder uriBuilder, String blobId, String username) throws URISyntaxException {
    AccessToken accessToken = userStepdefs.authenticate(username);
    AttachmentAccessTokenKey key = new AttachmentAccessTokenKey(username, blobId);
    uriBuilder.addParameter("access_token", attachmentAccessTokens.get(key).serialize());
    return Request.Get(uriBuilder.build());
}
 
Example 17
Source File: HttpClientUtils.java    From smockin with Apache License 2.0 2 votes vote down vote up
public static HttpClientResponseDTO get(final HttpClientCallDTO reqDto) throws IOException {

        final Request request = Request.Get(reqDto.getUrl());

        return executeRequest(request, reqDto.getHeaders());
    }
 
Example 18
Source File: HttpClientServiceImpl.java    From smockin with Apache License 2.0 2 votes vote down vote up
HttpClientResponseDTO get(final HttpClientCallDTO reqDto) throws IOException {

        final Request request = Request.Get(reqDto.getUrl());

        return executeRequest(request, reqDto.getHeaders(), isHttps(reqDto.getUrl()));
    }