下面列出了org.apache.http.client.fluent.Request#Get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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;
}
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<>();
}
}
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);
}
}
@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")));
}
@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")));
}
@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")));
}
@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")));
}
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;
}
/**
* 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();
}
/**
* 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;
}
@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")));
}
@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();
}
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;
}
/**
* 下载文件
* @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;
}
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;
}
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());
}
HttpClientResponseDTO get(final HttpClientCallDTO reqDto) throws IOException {
final Request request = Request.Get(reqDto.getUrl());
return executeRequest(request, reqDto.getHeaders(), isHttps(reqDto.getUrl()));
}
public static HttpClientResponseDTO get(final HttpClientCallDTO reqDto) throws IOException {
final Request request = Request.Get(reqDto.getUrl());
return executeRequest(request, reqDto.getHeaders());
}