List of usage examples for org.apache.http.impl.client CloseableHttpClient execute
public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException
From source file:org.wuspba.ctams.ws.ITBandContestEntryController.java
protected static void delete() throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH) .setParameter("id", TestFixture.INSTANCE.bandContestEntry.getId()).build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try {/*from w ww . j a v a 2 s.com*/ response = httpclient.execute(httpDelete); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } ITBandContestController.delete(); ITBandController.delete(); ITVenueController.delete(); ITJudgeController.delete(); }
From source file:org.wuspba.ctams.ws.ITSoloContestEntryController.java
protected static void delete() throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH) .setParameter("id", TestFixture.INSTANCE.soloContestEntry.getId()).build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try {/* w ww. jav a2s . co m*/ response = httpclient.execute(httpDelete); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } ITSoloContestController.delete(); ITPersonController.delete(); ITVenueController.delete(); ITJudgeController.delete(); }
From source file:erainformatica.utility.JSONHelper.java
public static TelegramRequestResult<JSONObject> readJsonFromUrl(String url, InputFile file) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost uploadFile = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); //builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN); builder.addBinaryBody(file.getName(), file.getFile_content(), ContentType.APPLICATION_OCTET_STREAM, file.getName() + "." + file.getExtension()); HttpEntity multipart = builder.build(); uploadFile.setEntity(multipart);/*w w w .j a v a 2 s . c om*/ CloseableHttpResponse response = null; try { response = httpClient.execute(uploadFile); } catch (IOException ex) { Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex); } HttpEntity responseEntity = response.getEntity(); try { return readJsonFromInputStream(responseEntity.getContent()); } catch (Exception ex) { return new TelegramRequestResult<>(false, ex.toString(), null); } }
From source file:nl.knaw.dans.easy.sword2examples.Common.java
static URI trackDeposit(CloseableHttpClient http, URI statUri) throws Exception { CloseableHttpResponse response;//w w w .ja v a 2 s .c o m String bodyText; System.out.println( "Start polling Stat-IRI for the current status of the deposit, waiting 10 seconds before every request ..."); while (true) { Thread.sleep(10000); System.out.print("Checking deposit status ... "); response = http.execute(new HttpGet(statUri)); if (response.getStatusLine().getStatusCode() != 200) { System.out.println("Stat-IRI returned " + response.getStatusLine().getStatusCode()); System.exit(1); } bodyText = readEntityAsString(response.getEntity()); Feed statement = parse(bodyText); List<Category> states = statement.getCategories("http://purl.org/net/sword/terms/state"); if (states.isEmpty()) { System.err.println("ERROR: NO STATE FOUND"); System.exit(1); } else if (states.size() > 1) { System.err.println("ERROR: FOUND TOO MANY STATES (" + states.size() + "). CAN ONLY HANDLE ONE"); System.exit(1); } else { String state = states.get(0).getTerm(); System.out.println(state); if (state.equals("INVALID") || state.equals("REJECTED") || state.equals("FAILED")) { System.err.println("FAILURE. Complete statement follows:"); System.err.println(bodyText); System.exit(3); } else if (state.equals("ARCHIVED")) { List<Entry> entries = statement.getEntries(); System.out.println("SUCCESS. "); if (entries.size() == 1) { System.out.print("Deposit has been archived at: <" + entries.get(0).getId() + ">. "); List<String> dois = getDois(entries.get(0)); int numDois = dois.size(); switch (numDois) { case 1: System.out.print(" With DOI: [" + dois.get(0) + "]. "); break; case 0: System.out.println("WARNING: No DOI found"); break; default: System.out.println("WARNING: More than one DOI found (" + numDois + "): "); boolean first = true; for (String doi : dois) { if (first) first = false; else System.out.print(", "); System.out.print(doi + ""); } System.out.println(); break; } } else { System.out.println( "WARNING: Found (" + entries.size() + ") entry's; should be ONE and only ONE"); } String stateText = states.get(0).getText(); System.out.println("Dataset landing page will be located at: <" + stateText + ">."); System.out.println("Complete statement follows:"); System.out.println(bodyText); return entries.get(0).getId().toURI(); } } } }
From source file:org.apache.ofbiz.passport.event.LinkedInEvents.java
/** * Parse LinkedIn login response and login the user if possible. * /*from ww w . j ava2s . c o m*/ * @return */ public static String parseLinkedInResponse(HttpServletRequest request, HttpServletResponse response) { String authorizationCode = request.getParameter(PassportUtil.COMMON_CODE); String state = request.getParameter(PassportUtil.COMMON_STATE); if (!state.equals(request.getSession().getAttribute(SESSION_LINKEDIN_STATE))) { String errMsg = UtilProperties.getMessage(resource, "LinkedInFailedToMatchState", UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } if (UtilValidate.isEmpty(authorizationCode)) { String error = request.getParameter(PassportUtil.COMMON_ERROR); String errorDescpriton = request.getParameter(PassportUtil.COMMON_ERROR_DESCRIPTION); String errMsg = null; try { errMsg = UtilProperties.getMessage(resource, "FailedToGetLinkedInAuthorizationCode", UtilMisc.toMap(PassportUtil.COMMON_ERROR, error, PassportUtil.COMMON_ERROR_DESCRIPTION, URLDecoder.decode(errorDescpriton, "UTF-8")), UtilHttp.getLocale(request)); } catch (UnsupportedEncodingException e) { errMsg = UtilProperties.getMessage(resource, "GetLinkedInAuthorizationCodeError", UtilHttp.getLocale(request)); } request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } // Debug.logInfo("LinkedIn authorization code: " + authorizationCode, module); GenericValue oauth2LinkedIn = getOAuth2LinkedInConfig(request); if (UtilValidate.isEmpty(oauth2LinkedIn)) { String errMsg = UtilProperties.getMessage(resource, "GetOAuth2LinkedInConfigError", UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } String clientId = oauth2LinkedIn.getString(PassportUtil.ApiKeyLabel); String secret = oauth2LinkedIn.getString(PassportUtil.SecretKeyLabel); String returnURI = oauth2LinkedIn.getString(envPrefix + PassportUtil.ReturnUrlLabel); // Grant token from authorization code and oauth2 token // Use the authorization code to obtain an access token String accessToken = null; try { URI uri = new URIBuilder().setScheme(TokenEndpoint.substring(0, TokenEndpoint.indexOf(":"))) .setHost(TokenEndpoint.substring(TokenEndpoint.indexOf(":") + 3)).setPath(TokenServiceUri) .setParameter("client_id", clientId).setParameter("client_secret", secret) .setParameter("grant_type", "authorization_code").setParameter("code", authorizationCode) .setParameter("redirect_uri", returnURI).build(); HttpPost postMethod = new HttpPost(uri); CloseableHttpClient jsonClient = HttpClients.custom().build(); // Debug.logInfo("LinkedIn get access token query string: " + postMethod.getURI(), module); postMethod.setConfig(PassportUtil.StandardRequestConfig); CloseableHttpResponse postResponse = jsonClient.execute(postMethod); String responseString = new BasicResponseHandler().handleResponse(postResponse); // Debug.logInfo("LinkedIn get access token response code: " + postResponse.getStatusLine().getStatusCode(), module); // Debug.logInfo("LinkedIn get access token response content: " + responseString, module); if (postResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // Debug.logInfo("Json Response from LinkedIn: " + responseString, module); JSON jsonObject = JSON.from(responseString); JSONToMap jsonMap = new JSONToMap(); Map<String, Object> userMap = jsonMap.convert(jsonObject); accessToken = (String) userMap.get("access_token"); // Debug.logInfo("Generated Access Token : " + accessToken, module); } else { String errMsg = UtilProperties.getMessage(resource, "GetOAuth2LinkedInAccessTokenError", UtilMisc.toMap("error", responseString), UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } } catch (UnsupportedEncodingException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (IOException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (ConversionException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (URISyntaxException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } // Get User Profile HttpGet getMethod = new HttpGet(TokenEndpoint + UserApiUri + "?oauth2_access_token=" + accessToken); Document userInfo = null; try { userInfo = LinkedInAuthenticator.getUserInfo(getMethod, UtilHttp.getLocale(request)); } catch (IOException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (AuthenticatorException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (SAXException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (ParserConfigurationException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } finally { getMethod.releaseConnection(); } // Debug.logInfo("LinkedIn User Info:" + userInfo, module); // Store the user info and check login the user return checkLoginLinkedInUser(request, userInfo, accessToken); }
From source file:com.fufang.httprequest.HttpPostBuild.java
public static String postBuildJson(String url, String params) throws UnsupportedEncodingException, ClientProtocolException, IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); String postResult = null;//from w ww.j a va 2 s . com HttpPost httpPost = new HttpPost(url); System.out.println(" request " + httpPost.getRequestLine()); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000) .build(); httpPost.setConfig(requestConfig); StringEntity entity = new StringEntity(params.toString(), "UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); try { HttpResponse response = httpClient.execute(httpPost); int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity responseEntity = response.getEntity(); postResult = EntityUtils.toString(responseEntity); } else { System.out.println("unexpected response status - " + status); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return postResult; }
From source file:eionet.gdem.qa.functions.Json.java
/** * Method converts the URL response body into XML format and returns it as String. If the response is not in JSON format, then JsonError object is converted to XML. * @param requestUrl Request URL to JSON format content. * @return String of XML//w w w .j av a 2 s. c om */ public static String jsonRequest2xmlString(String requestUrl) { JsonError error = null; String responseString = null; String xml = null; HttpGet method = null; // Create an instance of HttpClient. CloseableHttpClient client = HttpClients.custom() .setRetryHandler(new DefaultHttpRequestRetryHandler(3, false)).build(); CloseableHttpResponse response = null; try { // Create a method instance. method = new HttpGet(requestUrl); // Provide custom retry handler is necessary //method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Execute the method. response = client.execute(method); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { LOGGER.error("Method failed: " + response.getStatusLine()); error = new JsonError(statusCode, response.getStatusLine().getReasonPhrase()); } else { // Read the response body. HttpEntity entity = response.getEntity(); byte[] responseBody = IOUtils.toByteArray(entity.getContent()); responseString = new String(responseBody, "UTF-8"); } /*} catch (HttpException e) { LOGGER.error("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); error = new JsonError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Fatal protocol violation.");*/ } catch (IOException e) { LOGGER.error("Fatal transport error: " + e.getMessage()); error = new JsonError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Fatal transport error."); e.printStackTrace(); } catch (Exception e) { LOGGER.error("Error: " + e.getMessage()); e.printStackTrace(); error = new JsonError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Error." + e.getMessage()); } finally { // Release the connection. if (method != null) { method.releaseConnection(); } } if (responseString != null) { xml = jsonString2xml(responseString); } else if (error != null) { xml = jsonString2xml(error); } else { xml = jsonString2xml(new JsonError()); } return xml; }
From source file:com.beginner.core.utils.HttpUtil.java
/** * <p>To request the POST way.</p> * /* ww w . j av a2s . c o m*/ * @param url request URI * @param json request parameter(json format string) * @param timeout request timeout time in milliseconds(The default timeout time for 30 seconds.) * @return String response result * @throws Exception * @since 1.0.0 */ public static String post(String url, String json, Integer timeout) throws Exception { // Validates input if (StringUtils.isBlank(url)) throw new IllegalArgumentException("The url cannot be null and cannot be empty."); //The default timeout time for 30 seconds if (null == timeout) timeout = 30000; String result = null; CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; try { httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).build(); HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); httpPost.setHeader("Content-Type", "text/plain"); httpPost.setEntity(new StringEntity(json, "UTF-8")); httpResponse = httpClient.execute(httpPost); HttpEntity entity = httpResponse.getEntity(); result = EntityUtils.toString(entity); EntityUtils.consume(entity); } catch (Exception e) { logger.error("POST?", e); return null; } finally { if (null != httpResponse) httpResponse.close(); if (null != httpClient) httpClient.close(); } return result; }
From source file:org.earthtime.archivingTools.IEDACredentialsValidator.java
private static Document HTTP_PostAndResponse(String userName, String password, String credentialsService) { Document doc = null;/*from w w w . j a va2 s.c o m*/ Map<String, String> dataToPost = new HashMap<>(); dataToPost.put("username", userName); dataToPost.put("password", password); CloseableHttpClient httpclient = HttpClients.createDefault(); org.apache.http.client.methods.HttpPost httpPost = new HttpPost(credentialsService); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("username", userName)); nameValuePairs.add(new BasicNameValuePair("password", password)); CloseableHttpResponse httpResponse = null; try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpResponse = httpclient.execute(httpPost); HttpEntity myEntity = httpResponse.getEntity(); InputStream response = myEntity.getContent(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); try { doc = factory.newDocumentBuilder().parse(response); //System.out.println("CCCC" + doc.getElementsByTagName("valid").item(0).getTextContent().trim()); } catch (ParserConfigurationException | SAXException | IOException parserConfigurationException) { System.out.println("PARSE error " + parserConfigurationException.getMessage()); } EntityUtils.consume(myEntity); } catch (IOException iOException) { } finally { try { httpResponse.close(); } catch (IOException iOException) { } } return doc; }
From source file:com.zhch.example.commons.http.v4_5.ClientExecuteProxy.java
public static void proxyExample() throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {/*from w ww . ja v a 2 s . co m*/ HttpHost proxy = new HttpHost("24.157.37.61", 8080, "http"); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); HttpGet request = new HttpGet("http://www.ip.cn"); request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1"); request.setConfig(config); System.out.println( "Executing request " + request.getRequestLine() + " to " + request.getURI() + " via " + proxy); CloseableHttpResponse response = httpclient.execute(request); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity(), "utf8")); } finally { response.close(); } } finally { httpclient.close(); } }