List of usage examples for org.apache.http.impl.client CloseableHttpClient execute
public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException
From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java
/** * Do delete.//w w w . j av a 2s . c o m * * @param uri the uri * @param headers the headers * @return the http get simple resp * @throws ClientProtocolException the client protocol exception * @throws IOException Signals that an I/O exception has occurred. * @throws HttpResponseException the http response exception */ public static HttpGetSimpleResp doDelete(String uri, HashMap<String, String> headers) throws ClientProtocolException, IOException, HttpResponseException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGetSimpleResp resp = new HttpGetSimpleResp(); try { HttpDelete httpDelete = new HttpDelete(uri); for (String key : headers.keySet()) { httpDelete.addHeader(key, headers.get(key)); } CloseableHttpResponse response = httpclient.execute(httpDelete); resp.setStatusCode(response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) { try { HttpEntity entity = response.getEntity(); if (entity != null) { // TODO to use for performance in the future resp.setResult(new BasicResponseHandler().handleResponse(response)); } EntityUtils.consume(entity); } finally { response.close(); } } else { // TODO optimiz (repeating code) throw new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); } } finally { httpclient.close(); } return resp; }
From source file:org.wso2.am.integration.test.utils.http.HTTPSClientUtils.java
/** * POST function implementation/* w ww . ja va2s. com*/ * * @param httpClient http client to use * @param url request URL * @param headers headers to be send * @param body payload to be send * @return org.apache.http.HttpResponse * @throws IOException if connection issue occurred */ private static HttpResponse sendPOSTMessage(CloseableHttpClient httpClient, String url, Map<String, String> headers, String body) throws IOException { HttpPost post = new HttpPost(url); if (headers != null) { for (Map.Entry<String, String> head : headers.entrySet()) { post.addHeader(head.getKey(), head.getValue()); } } post.setEntity(new StringEntity(body)); return httpClient.execute(post); }
From source file:zz.pseas.ghost.login.weibo.SinaWeiboLogin.java
public static String getSinaCookie(String username, String password) throws Exception { StringBuilder sb = new StringBuilder(); HtmlUnitDriver driver = new HtmlUnitDriver(true); // driver.setSocksProxy("127.0.0.1", 1080); // driver.setProxy("127.0.0.1", 1080); // HtmlOption htmlOption=new Ht // WebDriver driver = new FirefoxDriver(); driver.setJavascriptEnabled(true);/*from w w w . j av a 2s .c o m*/ // user agent switcher// String loginAddress = "http://login.weibo.cn/login/"; driver.get(loginAddress); WebElement ele = driver.findElementByCssSelector("img"); String src = ele.getAttribute("src"); String cookie = concatCookie(driver); CloseableHttpClient httpclient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(1000) .setCookieSpec(cookie).build(); HttpGet httpget = new HttpGet(src); httpget.setConfig(requestConfig); CloseableHttpResponse response = httpclient.execute(httpget); HttpEntity entity; String result = null; try { if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) { // try again// } entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { // do something useful InputStream inputStream = entity.getContent(); BufferedImage img = ImageIO.read(inputStream); // deal with the weibo captcha // String picName = LoginUtils.getCurrentTime("yyyyMMdd-hhmmss"); // captcha// LoginUtils.getCaptchaDir(); picName = "./captcha/captcha-" + picName + ".png"; ImageIO.write(img, "png", new File(picName)); String userInput = new CaptchaFrame(img).getUserInput(); WebElement mobile = driver.findElementByCssSelector("input[name=mobile]"); mobile.sendKeys(username); WebElement pass = driver.findElementByCssSelector("input[name^=password]"); pass.sendKeys(password); WebElement code = driver.findElementByCssSelector("input[name=code]"); code.sendKeys(userInput); WebElement rem = driver.findElementByCssSelector("input[name=remember]"); rem.click(); WebElement submit = driver.findElementByCssSelector("input[name=submit]"); // ?// submit.click(); result = concatCookie(driver); driver.close(); } finally { instream.close(); } } } finally { response.close(); } if (result.contains("gsid_CTandWM")) { return result; } else { // throw new Exception("weibo login failed"); return null; } }
From source file:org.aludratest.cloud.selenium.impl.SeleniumResourceImpl.java
private static List<String> getSelenium2SessionIds(String originalUrl) throws IOException { CloseableHttpClient client = HttpClientBuilder.create().build(); String baseUrl = originalUrl + "/wd/hub/sessions"; List<String> result = new ArrayList<String>(); try {//www. j a v a 2s .c o m HttpGet getMethod = new HttpGet(baseUrl); HttpResponse response = client.execute(getMethod); JSONObject sessions = extractJSONObject(response); if (sessions != null) { JSONArray array = sessions.getJSONArray("value"); for (int i = 0; i < array.length(); i++) { JSONObject obj = array.getJSONObject(i); result.add(obj.getString("id")); } } } catch (IOException e) { // ignore silently } catch (JSONException e) { // ignore silently } finally { IOUtils.closeQuietly(client); } return result; }
From source file:org.everit.authentication.cas.ecm.tests.SampleApp.java
/** * Ping CAS login URL./* w w w . j a v a 2 s . com*/ */ public static void pingCasLoginUrl(final BundleContext bundleContext) throws Exception { CloseableHttpClient httpClient = new SecureHttpClient(null, bundleContext).getHttpClient(); HttpGet httpGet = new HttpGet(CAS_LOGIN_URL + "?" + LOCALE); HttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpGet); Assert.assertEquals(CAS_PING_FAILURE_MESSAGE, HttpServletResponse.SC_OK, httpResponse.getStatusLine().getStatusCode()); } catch (Exception e) { LOGGER.error(CAS_PING_FAILURE_MESSAGE, e); Assert.fail(CAS_PING_FAILURE_MESSAGE); } finally { if (httpResponse != null) { EntityUtils.consume(httpResponse.getEntity()); } httpClient.close(); } }
From source file:ch.ralscha.extdirectspring_itest.RawJsonControllerTest.java
@SuppressWarnings("unchecked") private static void testAndCheck(String action, String method, Integer total, boolean success) throws IOException, JsonParseException, JsonMappingException { CloseableHttpClient client = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try {//from w w w .jav a 2 s . co m HttpPost post = new HttpPost("http://localhost:9998/controller/router"); StringEntity postEntity = new StringEntity("{\"action\":\"" + action + "\",\"method\":\"" + method + "\",\"data\":[],\"type\":\"rpc\",\"tid\":1}", "UTF-8"); post.setEntity(postEntity); post.setHeader("Content-Type", "application/json; charset=UTF-8"); response = client.execute(post); HttpEntity entity = response.getEntity(); assertThat(entity).isNotNull(); String responseString = EntityUtils.toString(entity); assertThat(responseString).isNotNull(); assertThat(responseString).startsWith("[").endsWith("]"); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> rootAsMap = mapper .readValue(responseString.substring(1, responseString.length() - 1), Map.class); assertEquals(5, rootAsMap.size()); assertEquals(method, rootAsMap.get("method")); assertEquals("rpc", rootAsMap.get("type")); assertEquals(action, rootAsMap.get("action")); assertEquals(1, rootAsMap.get("tid")); Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result"); if (total != null) { assertEquals(3, result.size()); assertThat((Integer) result.get("total")).isEqualTo(total); } else { assertEquals(2, result.size()); } assertThat((Boolean) result.get("success")).isEqualTo(success); List<Map<String, Object>> records = (List<Map<String, Object>>) result.get("records"); assertEquals(2, records.size()); assertEquals("4cf8e5b8924e23349fb99454", ((Map<String, Object>) records.get(0).get("_id")).get("$oid")); assertEquals("4cf8e5b8924e2334a0b99454", ((Map<String, Object>) records.get(1).get("_id")).get("$oid")); } finally { IOUtils.closeQuietly(response); IOUtils.closeQuietly(client); } }
From source file:com.ecofactor.qa.automation.consumerapi.dr.HTTPSClient.java
/** * Put response./*from ww w . j av a 2 s . c o m*/ * * @param url the url * @param json the json * @param httpClient the http client * @return the http response */ public static synchronized HttpResponse putResponse(final String url, final String json, final CloseableHttpClient httpClient) { try { checkHTTPClient(httpClient); final HttpPut httpPut = new HttpPut(url); httpPut.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); httpPut.setHeader(HttpHeaders.ACCEPT, "application/json"); final StringEntity params = new StringEntity(json); httpPut.setEntity(params); final CloseableHttpResponse response = httpClient.execute(httpPut); setLogString("Status == " + response.getStatusLine(), true); return response; } catch (IOException | HTTPClientException e) { setLogString("Error executing HTTPS method. Reason ::: " + e, true); return null; } }
From source file:com.ecofactor.qa.automation.drapi.HTTPSClient.java
/** * Put response./*from w w w. j av a2s . c o m*/ * @param url the url * @param json the json * @param httpClient the http client * @return the http response */ public static synchronized HttpResponse putResponse(final String url, final String json, final CloseableHttpClient httpClient) { try { checkHTTPClient(httpClient); final HttpPut httpPut = new HttpPut(url); httpPut.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); httpPut.setHeader(HttpHeaders.ACCEPT, "application/json"); final StringEntity params = new StringEntity(json); httpPut.setEntity(params); final CloseableHttpResponse response = httpClient.execute(httpPut); setLogString("URL Values of the API \n" + url + "\n" + json, true); setLogString("Status == " + response.getStatusLine(), true); // setLogString("response " + response, true); return response; } catch (IOException | HTTPClientException e) { setLogString("Error executing HTTPS method. Reason ::: " + e, true); return null; } }
From source file:co.aurasphere.botmill.fb.internal.util.network.NetworkUtils.java
/** * Sends a request./* ww w. j ava 2 s. c o m*/ * * @param request * the request to send * @return response the response. */ private static String send(HttpRequestBase request) { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); logger.debug(request.getRequestLine().toString()); HttpResponse httpResponse = null; String response = null; try { httpResponse = httpClient.execute(request); response = logResponse(httpResponse); } catch (Exception e) { logger.error("Error during HTTP connection to Facebook: ", e); } finally { try { httpClient.close(); } catch (IOException e) { logger.error("Error while closing HTTP connection: ", e); } } return response; }
From source file:com.ecofactor.qa.automation.consumerapi.dr.HTTPSClient.java
/** * Post response.// w w w . j a v a 2 s.c om * * @param url the url * @param json the json * @param httpClient the http client * @return the http response */ public static synchronized HttpResponse postResponse(final String url, final String json, final CloseableHttpClient httpClient) { try { checkHTTPClient(httpClient); final HttpPost httpPost = new HttpPost(url); httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); httpPost.setHeader(HttpHeaders.ACCEPT, "application/json"); final StringEntity params = new StringEntity(json); httpPost.setEntity(params); final CloseableHttpResponse response = httpClient.execute(httpPost); setLogString("Status == " + response.getStatusLine(), true); return response; } catch (IOException | HTTPClientException e) { setLogString("Error executing HTTPS method. Reason ::: " + e, true); return null; } }