@Test public void client() throws URISyntaxException, IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder() .setScheme("http") .setHost("www.google.com") .setPath("/search") .setParameter("q", "httpclient") .setParameter("btnG", "Google Search") .setParameter("aq", "f") .setParameter("oq", "") .build(); HttpGet httpget = new HttpGet(uri); CloseableHttpResponse response = httpclient.execute(httpget); }
/** * sendGetCommand * * @param url * @param parameters * @return */ public Map<String, String> sendGetCommand(String url, Map<String, Object> parameters) throws ManagerResponseException { Map<String, String> response = new HashMap<String, String>(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(url); try { CloseableHttpResponse httpResponse = httpclient.execute(httpget, localContext); ResponseHandler<String> handler = new CustomResponseErrorHandler(); String body = handler.handleResponse(httpResponse); response.put(BODY, body); httpResponse.close(); } catch (Exception e) { throw new ManagerResponseException(e.getMessage(), e); } return response; }
@Override public String getJsonFromCAdvisor(String containerId) { String result = ""; try { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(cAdvisorURL + "/api/v1.3/containers/docker/" + containerId); CloseableHttpResponse response = httpclient.execute(httpget); try { result = EntityUtils.toString(response.getEntity()); if (logger.isDebugEnabled()) { logger.debug(result); } } finally { response.close(); } } catch (Exception e) { logger.error(containerId, e); } return result; }
public ReadAggregatesResult readAggregates() throws IOException, PyroclastAPIException { ensureBaseAttributes(); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { String url = String.format("%s/%s/aggregates", this.buildEndpoint(), this.deploymentId); HttpGet httpGet = new HttpGet(url); httpGet.addHeader("Authorization", this.readApiKey); httpGet.addHeader("Content-type", FORMAT); ReadAggregatesResult result; try (CloseableHttpResponse response = httpClient.execute(httpGet)) { ResponseParser<ReadAggregatesResult> parser = new ReadAggregatesParser(); result = parser.parseResponse(response, MAPPER); } return result; } }
@Test public void should_return_status_corresponding_to_match() throws IOException { HttpClientMock httpClientMock = new HttpClientMock("http://localhost:8080"); httpClientMock.onGet("/login").doReturnStatus(200); httpClientMock.onGet("/abc").doReturnStatus(404); httpClientMock.onGet("/error").doReturnStatus(500); HttpResponse ok = httpClientMock.execute(new HttpGet("http://localhost:8080/login")); HttpResponse notFound = httpClientMock.execute(new HttpGet("http://localhost:8080/abc")); HttpResponse error = httpClientMock.execute(new HttpGet("http://localhost:8080/error")); assertThat(ok, hasStatus(200)); assertThat(notFound, hasStatus(404)); assertThat(error, hasStatus(500)); }
@SuppressWarnings("unchecked") @Test public void shouldCreateRequestAttachment() throws Exception { final AttachmentRenderer<AttachmentData> renderer = mock(AttachmentRenderer.class); final AttachmentProcessor<AttachmentData> processor = mock(AttachmentProcessor.class); final HttpClientBuilder builder = HttpClientBuilder.create() .addInterceptorLast(new AllureHttpClientRequest(renderer, processor)); try (CloseableHttpClient httpClient = builder.build()) { final HttpGet httpGet = new HttpGet(String.format("http://localhost:%d/hello", server.port())); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { response.getStatusLine().getStatusCode(); } } final ArgumentCaptor<AttachmentData> captor = ArgumentCaptor.forClass(AttachmentData.class); verify(processor, times(1)) .addAttachment(captor.capture(), eq(renderer)); assertThat(captor.getAllValues()) .hasSize(1) .extracting("url") .containsExactly("/hello"); }
private User getUser(@NotNull Token token) throws IOException, URISyntaxException { URIBuilder builder = new URIBuilder(PROFILE_URL); builder.addParameter("access_token", token.getAccessToken()); HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet httpGet = new HttpGet(builder.build()); org.apache.http.HttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); InputStream inputStream = response.getEntity().getContent(); if (HttpUtilities.success(statusCode)) { User user = gson.fromJson(new InputStreamReader(inputStream), User.class); user.setToken(token); return user; } throw new ApiException(HttpStatus.valueOf(statusCode)); }
public static String check_email_exist(String email_addr) throws Exception { HttpClient client = new DefaultHttpClient(); String params = "?email_addr=" + email_addr; HttpGet get = new HttpGet(url + "/check_email_exist" + params); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = null; HttpEntity entity = response.getEntity(); if (entity != null) { result = EntityUtils.toString(entity); } JSONObject jsonObject = new JSONObject(result); int email_exists = jsonObject.getInt("email_exists"); if (email_exists == 1) { return "SUCCESS"; } else return "FAIL"; } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { return "401 SC_UNAUTHORIZED"; } return "UNKNOWN ERROR"; }
private void CheckForListOfUsersReturned(ArrayList<User> userList, HttpGet method, String responseString, String headerString, String responseStatus, ArrayList<String> subTests) throws CharonException, ComplianceException, GeneralComplianceException { subTests.add(ComplianceConstants.TestConstants.PAGINATION_USER_TEST); if (userList.size() != 2){ //clean up task for (String id : userIDs) { CleanUpUser(id); } throw new GeneralComplianceException(new TestResult(TestResult.ERROR, "Pagination Users", "Response does not contain right number of pagination.", ComplianceUtils.getWire(method, responseString, headerString, responseStatus, subTests))); } }
@Ignore public void testRetryAsync3() throws Exception { final int TIME_OUT = 30000; ThreadPoolExecutor executor = RetryUtil.createThreadPoolExecutor(); String res = RetryUtil.asyncExecuteWithRetry(new Callable<String>() { @Override public String call() throws Exception { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIME_OUT) .setConnectTimeout(TIME_OUT).setConnectionRequestTimeout(TIME_OUT) .setStaleConnectionCheckEnabled(true).build(); HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(10).setMaxConnPerRoute(10) .setDefaultRequestConfig(requestConfig).build(); HttpGet httpGet = new HttpGet(); httpGet.setURI(new URI("http://0.0.0.0:8080/test")); httpClient.execute(httpGet); return OK; } }, 3, 1000L, false, 6000L, executor); Assert.assertEquals(res, OK); // Assert.assertEquals(RetryUtil.EXECUTOR.getActiveCount(), 0); }
@Override public T execute() throws ClientProtocolException, IOException { HttpGet get = new HttpGet(InstagramConstants.API_URL + getUrl()); get.addHeader("Connection", "close"); get.addHeader("Accept", "*/*"); get.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); get.addHeader("Cookie2", "$Version=1"); get.addHeader("Accept-Language", "en-US"); get.addHeader("User-Agent", InstagramConstants.USER_AGENT); HttpResponse response = api.getClient().execute(get); api.setLastResponse(response); int resultCode = response.getStatusLine().getStatusCode(); String content = EntityUtils.toString(response.getEntity()); get.releaseConnection(); return parseResult(resultCode, content); }
/** * get the csrf token from the login page's http form * * @return the csrf token * * @throws IOException * @param forwardedForHeader */ private String getCsrfToken(Header forwardedForHeader) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpGet httpGet = new HttpGet(configuration.getLoginUrl()); httpGet.setHeader(forwardedForHeader); CloseableHttpResponse response1 = httpclient.execute(httpGet, context); try { logger.debug(response1.getStatusLine().toString()); Optional<String> csrfTokenOpt = extractCsrfTokenAndCloseConnection(response1); return csrfTokenOpt.orElseThrow( () -> new IllegalStateException("failed to extract csrf token.")); } finally { response1.close(); } } finally { httpclient.close(); } }
@Test public void should_use_right_host_and_path() throws IOException { HttpClientMock httpClientMock = new HttpClientMock(); httpClientMock.onGet("http://localhost:8080/foo").doReturn("localhost"); httpClientMock.onGet("http://www.google.com").doReturn("google"); httpClientMock.onGet("https://www.google.com").doReturn("https"); HttpResponse localhost = httpClientMock.execute(new HttpGet("http://localhost:8080/foo")); HttpResponse google = httpClientMock.execute(new HttpGet("http://www.google.com")); HttpResponse https = httpClientMock.execute(new HttpGet("https://www.google.com")); assertThat(localhost, hasContent("localhost")); assertThat(google, hasContent("google")); assertThat(https, hasContent("https")); }
public static void main(String[] args) { final CrawlerHttpClient httpClient = HttpInvoker.buildDefault(); for (int i = 0; i < 20; i++) { new Thread() { @Override public void run() { HttpGet httpGet = new HttpGet("https://passport.jd.com/new/login.aspx"); RequestConfig.Builder builder = RequestConfig.custom() .setSocketTimeout(ProxyConstant.SOCKET_TIMEOUT) .setConnectTimeout(ProxyConstant.CONNECT_TIMEOUT) .setConnectionRequestTimeout(ProxyConstant.REQUEST_TIMEOUT).setRedirectsEnabled(true) .setCircularRedirectsAllowed(true); httpGet.setConfig(builder.build()); try { CloseableHttpResponse execute = httpClient.execute(httpGet); System.out.println(IOUtils.toString(execute.getEntity().getContent())); } catch (IOException e) { e.printStackTrace(); } } }.start(); } }
private JsonNode doNotificationsSearch(String query, String subsearch, Map<?, ?> otherParams, String token) throws Exception { List<NameValuePair> params = Lists.newArrayList(); if( query != null ) { params.add(new BasicNameValuePair("q", query)); } if( subsearch != null ) { params.add(new BasicNameValuePair("type", subsearch)); } for( Entry<?, ?> entry : otherParams.entrySet() ) { params.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString())); } String paramString = URLEncodedUtils.format(params, "UTF-8"); HttpGet get = new HttpGet(context.getBaseUrl() + "api/notification?" + paramString); HttpResponse response = execute(get, false, token); return mapper.readTree(response.getEntity().getContent()); }
@RequestMapping(value = "getAllMethod", method = RequestMethod.GET) public List<MethodDefinition> getAllMethod( @RequestParam(value = "ipPort", required = true) String ipPort, @RequestParam(value = "service", required = true) String service) throws Exception { String methdUrl = "http://" + ipPort + "/service/getAllMethod?service=" + service; HttpGet request = new HttpGet(methdUrl); request.addHeader("content-type", "application/json"); request.addHeader("Accept", "application/json"); try { HttpResponse httpResponse = httpClient.execute(request); if (httpResponse.getStatusLine().getStatusCode() == 200) { String minitorJson = EntityUtils.toString(httpResponse.getEntity()); List<MethodDefinition> allMethods = gson.fromJson(minitorJson, new TypeToken<List<MethodDefinition>>() {}.getType()); return allMethods; } } catch (Exception e) { throw e; } return null; }
/** * Wait for the server is ready. */ private void waitForServerReady() throws IOException, InterruptedException { final HttpGet httpget = new HttpGet(getPingUri()); HttpResponse response = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, "")); int counter = 0; while (true) { try { response = httpclient.execute(httpget); final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { break; } checkRetries(counter); } catch (final HttpHostConnectException ex) { // NOSONAR - Wait, and check later log.info("Check failed, retrying..."); checkRetries(counter); } finally { EntityUtils.consume(response.getEntity()); } counter++; } }
public double getUsdGbp() { HttpClientBuilder hcb = HttpClientBuilder.create(); HttpClient client = hcb.build(); HttpGet request = new HttpGet(RequestURI.baseURL+"/v1/prices?instruments=GBP_USD"); request.addHeader(RequestURI.headerTitle,RequestURI.accessToken); try { HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } JSONObject resultJson = new JSONObject(result.toString()); JSONArray priceDetails = resultJson.getJSONArray("prices"); resultJson = priceDetails.getJSONObject(0); double midPrice = (resultJson.getDouble("ask") + resultJson.getDouble("bid"))/2; return 1/midPrice; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; }
@Test public void contentEncoding() throws Exception { String text = "{\"Message\": { \"text\": \"Hello, World!\" } }"; server.enqueue(new MockResponse().setBody(gzip(text)) .setHeader("Content-Encoding", "gzip")); HttpGet request = new HttpGet(server.url("/").url().toURI()); request.setHeader("Accept-encoding", "gzip"); // Not transparent gzip. HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); Header[] encodingHeaders = response.getHeaders("Content-Encoding"); assertEquals(1, encodingHeaders.length); assertEquals("gzip", encodingHeaders[0].getValue()); assertNotNull(entity.getContentEncoding()); assertEquals("gzip", entity.getContentEncoding().getValue()); assertEquals(text, gunzip(entity)); }
/** * Validate returned list of users. * @param userList * @param method * @param responseString * @param headerString * @param responseStatus * @param subTests * @throws CharonException * @throws ComplianceException * @throws GeneralComplianceException */ private void CheckForListOfUsersReturned(ArrayList<User> userList, HttpGet method, String responseString, String headerString, String responseStatus, ArrayList<String> subTests) throws CharonException, ComplianceException, GeneralComplianceException { subTests.add(ComplianceConstants.TestConstants.SORT_USERS_TEST); if(isUserListSorted(userList)) { //clean up task for (String id : userIDs.keySet()) { CleanUpUser(id); } throw new GeneralComplianceException(new TestResult(TestResult.ERROR, "Sort Users", "Response does not contain the sorted list of users", ComplianceUtils.getWire(method, responseString, headerString, responseStatus, subTests))); } }
public void get(final URI uri, final Consumer<InputStream> consumer) { execute(new HttpGet(uri), true, new Function<HttpEntity, Void>() { @Override public Void apply(HttpEntity entity, Set<Hint> hints) { if (entity == null) { throw new IllegalStateException("No response!"); } else { try (InputStream input = entity.getContent()) { consumer.accept(input); } catch (IOException e) { throw new IllegalStateException("Could not read response for URL: " + uri, e); } } return null; } }); }
private void retrieveAccessToken() throws IOException, WeiboClientException { String state = "__MY_STATE__"; String authorizationCallback = "https://api.weibo.com/oauth2/authorize"; String url = this.client.getAuthorizationUrl(ResponseType.Code, DisplayType.Default, state, authorizationCallback); //httpget CloseableHttpResponse response = null; HttpClientContext context = HttpClientContext.create(); HttpGet httpGet = new HttpGet(url); response = httpClient.execute(httpGet, context); // 获取所有的重定向位置 List<URI> redirectLocations = context.getRedirectLocations(); //end System.out.println("Please visit: " + url); System.out.print("Input code: "); in = new BufferedReader(new InputStreamReader(System.in)); String code = in.readLine(); String accessTokenCallback = "https://api.weibo.com/oauth2/authorize"; SinaWeibo2AccessToken accessToken = this.client.getAccessTokenByCode(code, accessTokenCallback); System.out.println(); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Uid: " + accessToken.getUid()); System.out.println("Expires in: " + accessToken.getExpiresIn()); System.out.println("Remind in: " + accessToken.getRemindIn()); accessToken = new SinaWeibo2AccessToken(accessToken.getToken()); this.client.setAccessToken(accessToken); }
/** * @see ExceptionMapperResource#throwWebApplication() */ @Test public void testJaxRS405Error() throws IOException { final HttpGet httpget = new HttpGet(BASE_URI + RESOURCE + "/jax-rs"); HttpResponse response = null; try { response = httpclient.execute(httpget); Assert.assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, response.getStatusLine().getStatusCode()); final String content = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); final Map<?, ?> result = new ObjectMapperTrim().readValue(content, HashMap.class); Assert.assertEquals("internal", result.get("code")); Assert.assertNull(result.get("cause")); Assert.assertEquals("HTTP 405 Method Not Allowed", result.get("message")); } finally { if (response != null) { response.getEntity().getContent().close(); } } }
@Override public String getJsonMachineFromCAdvisor() { String result = ""; try { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(cAdvisorURL + "/api/v1.3/machine"); CloseableHttpResponse response = httpclient.execute(httpget); try { result = EntityUtils.toString(response.getEntity()); if (logger.isDebugEnabled()) { logger.debug(result); } } finally { response.close(); } } catch (Exception e) { logger.error("" + e); } return result; }
@Test public void test1(){ try { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet( "http://hncjzf.bibibi.net/module/getcareers?start=0&count=50&keyword=&address=&professionals=&career_type=&type=inner&day=2017-11-08"); HttpResponse response = httpClient.execute(httpGet); JSONObject object = JSON.parseObject(EntityUtils.toString(response.getEntity())); JSONArray data = object.getJSONArray("data"); List<HUELList> list = JSON.parseArray(data.toJSONString(), HUELList.class); //HUELList list1 = list.get(0); huelService.saveList(list); }catch (IOException e){ } }
public void rawGet(String str, RawNetworkCallback rawNetworkCallback) throws Throwable { HttpUriRequest httpGet = new HttpGet(str); HttpClient sSLHttpClient = str.startsWith("https://") ? getSSLHttpClient() : new DefaultHttpClient(); HttpResponse execute = sSLHttpClient.execute(httpGet); int statusCode = execute.getStatusLine().getStatusCode(); if (statusCode == 200) { if (rawNetworkCallback != null) { rawNetworkCallback.onResponse(execute.getEntity().getContent()); } sSLHttpClient.getConnectionManager().shutdown(); return; } String entityUtils = EntityUtils.toString(execute.getEntity(), Constants.UTF_8); HashMap hashMap = new HashMap(); hashMap.put("error", entityUtils); hashMap.put("status", Integer.valueOf(statusCode)); sSLHttpClient.getConnectionManager().shutdown(); throw new Throwable(new Hashon().fromHashMap(hashMap)); }
public static double getBalance() { String temp; HttpClientBuilder hcb = HttpClientBuilder.create(); HttpClient client = hcb.build(); HttpGet request = new HttpGet(RequestURI.baseURL+"/v3/accounts/"+RequestURI.accountId+"/summary"); request.addHeader(RequestURI.headerTitle,RequestURI.accessToken); try { HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } JSONObject accountDetails = new JSONObject(result.toString()).getJSONObject("account"); temp = accountDetails.getString("balance"); return Double.parseDouble(temp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; }
public static String ticketQuery(TrainQuery trainQuery) { Objects.requireNonNull(trainQuery); CloseableHttpClient httpClient = buildHttpClient(); HttpGet httpGet = new HttpGet(UrlConfig.ticketQuery + "?" + genQueryParam(trainQuery)); httpGet.setHeader(CookieManager.cookieHeader()); String result = StringUtils.EMPTY; try(CloseableHttpResponse response = httpClient.execute(httpGet)) { CookieManager.touch(response); result = EntityUtils.toString(response.getEntity()); } catch (IOException e) { logger.error("ticketQuery error", e); } return result; }
/** * Get ERC20-Token account balance by contract address * @param contractAddress Contract address * @param address Address * @return ERC29-Token account balance */ public BigInteger getErc20TokenAccountBalance(String contractAddress, String address) { HttpGet get = new HttpGet(PUBLIC_URL + "?module=account&action=tokenbalance&contractaddress=" + contractAddress + "&address=" + address + "&tag=latest" + "&apikey=" + API_KEY); String response = null; try(CloseableHttpResponse httpResponse = httpClient.execute(get)) { HttpEntity httpEntity = httpResponse.getEntity(); response = EntityUtils.toString(httpEntity); EntityUtils.consume(httpEntity); } catch (IOException e) { e.printStackTrace(); } @SuppressWarnings("rawtypes") ArrayList<CustomNameValuePair<String, CustomNameValuePair>> a = Utility.evaluateExpression(response); for(int j = 0; j < a.size(); j++) if(a.get(j).getName().toString().equals("result")) return new BigInteger(a.get(j).getValue().toString()); return null; // Null should not be expected when API is functional }
/** * Validation test for list of users in the response. * @param userList * @param method * @param responseString * @param headerString * @param responseStatus * @param subTests * @throws CharonException * @throws ComplianceException * @throws GeneralComplianceException */ private void CheckForListOfUsersReturned(ArrayList<User> userList, HttpGet method, String responseString, String headerString, String responseStatus, ArrayList<String> subTests) throws CharonException, ComplianceException, GeneralComplianceException { subTests.add(ComplianceConstants.TestConstants.ALL_USERS_IN_TEST); ArrayList<String> returnedUserIDs = new ArrayList<>(); for (User user : userList) { returnedUserIDs.add(user.getId()); } for (String id : userIDs){ if (!returnedUserIDs.contains(id)){ //clean up task for (String userId : userIDs) { CleanUpUser(userId); } throw new GeneralComplianceException(new TestResult(TestResult.ERROR, "List Users", "Response does not contain all the created users", ComplianceUtils.getWire(method, responseString, headerString, responseStatus, subTests))); } } }
@SuppressWarnings("unchecked") public static String encontrarCoordenadas(String direccion) throws IOException{ HttpClient httpClient = new DefaultHttpClient(); HttpUriRequest request = new HttpGet("https://maps.googleapis.com/maps/api/geocode/json?address="+URLEncoder.encode(direccion, StandardCharsets.UTF_8.name())+"&key="+ TokensUtils.googleApiKey); HttpResponse res = httpClient.execute(request); Map<String, Object> resultadoJSON = (Map<String, Object>) new Gson().fromJson( new InputStreamReader(res.getEntity().getContent()), Map.class ); List<Map<String, Object>> results = (List<Map<String, Object>>) resultadoJSON.get("results"); if(!results.isEmpty()) { Map<String,Object> geometry = (Map<String,Object>) results.get(0).get("geometry"); Map<String,Object> location = (Map<String,Object>) geometry.get("location"); Double lat = (Double) location.get("lat"); Double lng = (Double) location.get("lng"); //texto.results[0].geometry.location.lat return lat+","+lng; }else{ return null; } }
@Test public void principalCacheHonorsTtl() throws Exception { HttpClient mockClient = fullyFunctionalMockClient(); GithubOauthConfiguration configWithShortCacheTtl = new MockGithubOauthConfiguration(Duration.ofMillis(1)); GithubApiClient clientToTest = new GithubApiClient(mockClient, configWithShortCacheTtl); char[] token = "DUMMY".toCharArray(); clientToTest.authz("demo-user", token); // We make 2 calls to Github for a single auth check Mockito.verify(mockClient, Mockito.times(2)).execute(Mockito.any(HttpGet.class)); Mockito.verifyNoMoreInteractions(mockClient); // Wait a bit for the cache to become invalidated Thread.sleep(10); // Mock the responses again so a second auth attempt works Mockito.reset(mockClient); mockResponsesForGithubAuthRequest(mockClient); // This should also hit Github because the cache TTL has elapsed clientToTest.authz("demo-user", token); // We make 2 calls to Github for a single auth check Mockito.verify(mockClient, Mockito.times(2)).execute(Mockito.any(HttpGet.class)); Mockito.verifyNoMoreInteractions(mockClient); }
public static String doGet(String url) throws Exception { try { CloseableHttpClient client = getHttpClient(url); HttpGet httpget = new HttpGet(url); config(httpget); logger.info("====> Executing request: " + httpget.getRequestLine()); String responseBody = client.execute(httpget, getStringResponseHandler()); logger.info("====> Getting response from request " + httpget.getRequestLine() + " The responseBody: " + responseBody); return responseBody; } catch (Exception e) { if (e instanceof HttpHostConnectException || e.getCause() instanceof ConnectException) { throw e; } logger.error("HttpRequestUtil.doGet: " + e.getMessage()); } return null; }
private String[] downloadConfig(String url) throws Exception { try { HttpClient client = new DefaultHttpClient(); HttpGet requestGet = new HttpGet(url); requestGet.addHeader("X-Android-MODEL", Build.MODEL); requestGet.addHeader("X-Android-SDK_INT", Integer.toString(Build.VERSION.SDK_INT)); requestGet.addHeader("X-Android-RELEASE", Build.VERSION.RELEASE); requestGet.addHeader("X-App-Version", AppVersion); requestGet.addHeader("X-App-Install-ID", AppInstallID); requestGet.setHeader("User-Agent", System.getProperty("http.agent")); HttpResponse response = client.execute(requestGet); String configString = EntityUtils.toString(response.getEntity(), "UTF-8"); String[] lines = configString.split("\\n"); return lines; } catch (Exception e) { throw new Exception(String.format("Download config file from %s failed.", url)); } }
public static JSONObject doGetJson(String url) { JSONObject jsonObject = null; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet= new HttpGet(url); try { HttpResponse response=httpClient.execute(httpGet); HttpEntity enyity=response.getEntity(); if (enyity != null) { String result=EntityUtils.toString(enyity,"UTF-8"); logger.info("JSONObject: {}",result); jsonObject=JSONObject.fromObject(result); } httpGet.releaseConnection(); } catch (IOException e) { logger.error("方法doGetJson失败:{}", e.getMessage()); } return jsonObject; }
public ReadAggregateResult readAggregate(String aggregateName) throws IOException, PyroclastAPIException { ensureBaseAttributes(); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { String url = String.format("%s/%s/aggregates/%s", this.buildEndpoint(), this.deploymentId, aggregateName); HttpGet httpGet = new HttpGet(url); httpGet.addHeader("Authorization", this.readApiKey); httpGet.addHeader("Content-type", FORMAT); ReadAggregateResult result; try (CloseableHttpResponse response = httpClient.execute(httpGet)) { ResponseParser<ReadAggregateResult> parser = new ReadAggregateParser(); result = parser.parseResponse(response, MAPPER); } return result; } }
@Test public void should_check_header() throws IOException { HttpClientMock httpClientMock = new HttpClientMock("http://localhost:8080"); httpClientMock.onGet("/login").doReturn("OK"); HttpGet getMozilla = new HttpGet("http://localhost:8080/login"); HttpGet getChrome = new HttpGet("http://localhost:8080/login"); getMozilla.addHeader("User-Agent", "Mozilla"); getChrome.addHeader("User-Agent", "Chrome"); httpClientMock.execute(getChrome); httpClientMock.execute(getMozilla); httpClientMock.verify().get("/login").withHeader("User-Agent", "Mozilla").called(); httpClientMock.verify().get("/login").withHeader("User-Agent", "Chrome").called(); httpClientMock.verify().get("/login").withHeader("User-Agent", "IE").notCalled(); }
/** * Get Token account balance by known Token name (Supported Token names: DGD, MKR, FirstBlood, HackerGold, ICONOMI, Pluton, REP, SNGLS) * @param tokenName Token name * @param address Address * @return Token account balance */ public BigInteger getTokenAccountBalance(String tokenName, String address) { HttpGet get = new HttpGet(PUBLIC_URL + "?module=account&action=tokenbalance&tokenname=" + tokenName + "&address=" + address + "&tag=latest" + "&apikey=" + API_KEY); String response = null; try(CloseableHttpResponse httpResponse = httpClient.execute(get)) { HttpEntity httpEntity = httpResponse.getEntity(); response = EntityUtils.toString(httpEntity); EntityUtils.consume(httpEntity); } catch (IOException e) { e.printStackTrace(); } @SuppressWarnings("rawtypes") ArrayList<CustomNameValuePair<String, CustomNameValuePair>> a = Utility.evaluateExpression(response); for(int j = 0; j < a.size(); j++) if(a.get(j).getName().toString().equals("result")) return new BigInteger(a.get(j).getValue().toString()); return null; // Null should not be expected when API is functional }
@Override protected String doInBackground(String... uri) { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response; String responseString = null; try { response = httpclient.execute(new HttpGet(uri[0])); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == 200) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); responseString = out.toString(); out.close(); } else { // Close the connection. response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (Exception e) { return null; } return responseString; }