List of usage examples for org.apache.http.client.methods CloseableHttpResponse getEntity
HttpEntity getEntity();
From source file:org.smartloli.kafka.eagle.common.util.HttpClientUtils.java
/** * Send request by post method.// www .ja v a 2 s. c o m * * @param uri: * http://ip:port/demo * @param parames: * new BasicNameValuePair("code", "200") * * new BasicNameValuePair("name", "smartloli") */ public static String doPostForm(String uri, List<BasicNameValuePair> parames) { String result = ""; try { CloseableHttpClient client = null; CloseableHttpResponse response = null; try { HttpPost httpPost = new HttpPost(uri); httpPost.setEntity(new UrlEncodedFormEntity(parames, "UTF-8")); client = HttpClients.createDefault(); response = client.execute(httpPost); HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); } finally { if (response != null) { response.close(); } if (client != null) { client.close(); } } } catch (Exception e) { e.printStackTrace(); LOG.error("Do post form request has error, msg is " + e.getMessage()); } return result; }
From source file:de.tu_dortmund.ub.data.util.TPUUtil.java
public static String getResponseMessage(final CloseableHttpResponse httpResponse) throws IOException { final HttpEntity httpEntity = httpResponse.getEntity(); final String response = getResponseMessage(httpEntity); EntityUtils.consume(httpEntity);/*from w w w.ja v a2 s .c o m*/ return response; }
From source file:utils.ImportExportUtils.java
/** * retrieve a access token with requested scope * * @param scope required token scope/*from w w w . java 2 s . c om*/ * @param consumerCredentials encoded consumerKey and consumerSecret */ static String getAccessToken(String scope, String consumerCredentials) { ApiImportExportConfiguration config = ApiImportExportConfiguration.getInstance(); String url = config.getGatewayUrl(); String responseString; //mapping payload to a List List<NameValuePair> params = new ArrayList<>(4); params.add(new BasicNameValuePair(ImportExportConstants.TOKEN_GRANT_TYPE, ImportExportConstants.DEFAULT_GRANT_TYPE)); params.add(new BasicNameValuePair(ImportExportConstants.USERNAME, config.getUsername())); params.add(new BasicNameValuePair(ImportExportConstants.DEFAULT_GRANT_TYPE, String.valueOf(config.getPassword()))); params.add(new BasicNameValuePair(ImportExportConstants.SCOPE_CONSTANT, scope)); //REST API call for get tokens CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate()); try { HttpPost request = new HttpPost(url); request.setEntity(new UrlEncodedFormEntity(params, ImportExportConstants.CHARSET)); request.setHeader(HttpHeaders.AUTHORIZATION, ImportExportConstants.AUTHORIZATION_KEY_SEGMENT + " " + consumerCredentials); CloseableHttpResponse response; response = client.execute(request); responseString = EntityUtils.toString(response.getEntity()); JSONObject jsonObj = (JSONObject) new JSONParser().parse(responseString); return ((String) jsonObj.get(ImportExportConstants.ACCESS_TOKEN)); } catch (ParseException e) { log.error("error occurred while getting the access token"); } catch (UnsupportedEncodingException | ClientProtocolException e) { String errormsg = "error occurred while passing the payload for token generation"; log.error(errormsg, e); return null; } catch (IOException e) { String errormsg = "error occurred while generating tokens"; log.error(errormsg, e); return null; } finally { IOUtils.closeQuietly(client); } return null; }
From source file:org.dashbuilder.dataprovider.backend.elasticsearch.ElasticSearchDataSetTestBase.java
protected static String responseAsString(CloseableHttpResponse response) throws IOException { return streamAsString(response.getEntity().getContent()); }
From source file:utils.TestUtils.java
public static String httpPost(String url, String data) throws Exception { CloseableHttpResponse resp = null; try {/*from www . j a v a 2 s . c o m*/ HttpPost post = new HttpPost(url); post.setEntity(new ByteArrayEntity(data.getBytes("UTF-8"))); resp = HTTP.execute(post); return EntityUtils.toString(resp.getEntity(), "UTF-8"); } finally { closeQuietly(resp); } }
From source file:org.sead.repositories.reference.util.SEADGoogleLogin.java
static void getAuthCode() { access_token = null;/*from w ww. j a va2 s. co m*/ expires_in = -1; token_start_time = -1; refresh_token = null; new File("refresh.txt").delete(); if (gProps == null) { initGProps(); } // Contact google for a user code CloseableHttpClient httpclient = HttpClients.createDefault(); try { String codeUri = gProps.auth_uri.substring(0, gProps.auth_uri.length() - 4) + "device/code"; HttpPost codeRequest = new HttpPost(codeUri); MultipartEntityBuilder meb = MultipartEntityBuilder.create(); meb.addTextBody("client_id", gProps.client_id); meb.addTextBody("scope", "email profile"); HttpEntity reqEntity = meb.build(); codeRequest.setEntity(reqEntity); CloseableHttpResponse response = httpclient.execute(codeRequest); try { if (response.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { String responseJSON = EntityUtils.toString(resEntity); ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON); device_code = root.get("device_code").asText(); user_code = root.get("user_code").asText(); verification_url = root.get("verification_url").asText(); expires_in = root.get("expires_in").asInt(); } } else { log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase()); } } finally { response.close(); httpclient.close(); } } catch (IOException e) { log.error("Error reading sead-google.json or making http requests for code."); log.error(e.getMessage()); } }
From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java
/** * Tries to retrieve the content for the specified node ID. * //from ww w. j av a 2s. co m * @param httpclient * the http client * @param nodeID * the node ID * @param authCookie * the session cookie to use for authentication purpose * @return the node content as JSON * @throws CommunityAPIException */ public static JsonNode retrieveNodeContentAsJSON(CloseableHttpClient httpclient, String nodeID, Cookie authCookie) throws CommunityAPIException { try { HttpGet retrieveNodeContentGET = new HttpGet( CommunityConstants.NODE_CONTENT_URL_PREFIX + nodeID + ".json"); //$NON-NLS-1$ CloseableHttpResponse resp = httpclient.execute(retrieveNodeContentGET); int httpRetCode = resp.getStatusLine().getStatusCode(); String responseBodyAsString = EntityUtils.toString(resp.getEntity()); if (HttpStatus.SC_OK == httpRetCode) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); JsonNode jsonRoot = mapper.readTree(responseBodyAsString); return jsonRoot; } else { CommunityAPIException ex = new CommunityAPIException( Messages.RESTCommunityHelper_NodeContentRetrieveError); ex.setHttpStatusCode(httpRetCode); ex.setResponseBodyAsString(responseBodyAsString); throw ex; } } catch (IOException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_GetMethodIOError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_NodeContentRetrieveError, e); } }
From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java
/** * Executes the authentication to the Jaspersoft community in order to * retrieve the session cookie to use later for all other operations. * /*from ww w .j a v a 2 s. c o m*/ * @param httpclient * the http client * * @param cookieStore * the Cookie Store instance * @param username * the community user name (or email) * @param password * the community user password * @return the authentication cookie if able to retrieve it, * <code>null</code> otherwise * @throws CommunityAPIException */ public static Cookie getAuthenticationCookie(CloseableHttpClient httpclient, CookieStore cookieStore, String username, String password) throws CommunityAPIException { try { HttpPost loginPOST = new HttpPost(CommunityConstants.LOGIN_URL); EntityBuilder loginEntity = EntityBuilder.create(); loginEntity.setText("{ \"username\": \"" + username + "\", \"password\":\"" + password + "\" }"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ loginEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE)); loginEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET); loginPOST.setEntity(loginEntity.build()); CloseableHttpResponse resp = httpclient.execute(loginPOST); int httpRetCode = resp.getStatusLine().getStatusCode(); String responseBodyAsString = EntityUtils.toString(resp.getEntity()); if (HttpStatus.SC_OK == httpRetCode) { // Can proceed List<Cookie> cookies = cookieStore.getCookies(); Cookie authCookie = null; for (Cookie cookie : cookies) { if (cookie.getName().startsWith("SESS")) { //$NON-NLS-1$ authCookie = cookie; break; } } return authCookie; } else if (HttpStatus.SC_UNAUTHORIZED == httpRetCode) { // Unauthorized... wrong username or password CommunityAPIException unauthorizedEx = new CommunityAPIException( Messages.RESTCommunityHelper_WrongUsernamePasswordError); unauthorizedEx.setHttpStatusCode(httpRetCode); unauthorizedEx.setResponseBodyAsString(responseBodyAsString); throw unauthorizedEx; } else { // Some other problem occurred CommunityAPIException generalEx = new CommunityAPIException( Messages.RESTCommunityHelper_AuthInfoProblemsError); generalEx.setHttpStatusCode(httpRetCode); generalEx.setResponseBodyAsString(responseBodyAsString); throw generalEx; } } catch (UnsupportedEncodingException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_AuthenticationError, e); } catch (IOException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_AuthenticationError, e); } }
From source file:org.commonjava.maven.galley.transport.htcli.internal.util.TransferResponseUtils.java
public static boolean handleUnsuccessfulResponse(final HttpUriRequest request, final CloseableHttpResponse response, HttpLocation location, final String url, final boolean graceful404) throws TransferException { final Logger logger = LoggerFactory.getLogger(TransferResponseUtils.class); final StatusLine line = response.getStatusLine(); InputStream in = null;/*from w ww. j av a 2s . c o m*/ HttpEntity entity = null; try { entity = response.getEntity(); final int sc = line.getStatusCode(); boolean contentMissing = (sc == HttpStatus.SC_NOT_FOUND || sc == HttpStatus.SC_GONE); if (graceful404 && contentMissing) { return false; } else { ByteArrayOutputStream out = null; if (entity != null) { in = entity.getContent(); out = new ByteArrayOutputStream(); copy(in, out); } if (NON_SERVER_GATEWAY_ERRORS.contains(sc) || (sc > 499 && sc < 599)) { throw new BadGatewayException(location, url, sc, "HTTP request failed: %s%s", line, (out == null ? "" : "\n\n" + new String(out.toByteArray()))); } else if (contentMissing) { throw new TransferException("HTTP request failed: %s\nURL: %s%s", line, url, (out == null ? "" : "\n\n" + new String(out.toByteArray()))); } else { throw new TransferLocationException(location, "HTTP request failed: %s%s", line, (out == null ? "" : "\n\n" + new String(out.toByteArray()))); } } } catch (final IOException e) { request.abort(); throw new TransferLocationException(location, "Error reading body of unsuccessful request.\nStatus: %s.\nURL: %s.\nReason: %s", e, line, url, e.getMessage()); } finally { IOUtils.closeQuietly(in); if (entity != null) { try { EntityUtils.consume(entity); } catch (final IOException e) { logger.debug("Failed to consume entity: " + e.getMessage(), e); } } } }
From source file:com.calmio.calm.integration.Helpers.HTTPHandler.java
public static HTTPResponseData sendGet(String url, String username, String pwd) throws Exception { CloseableHttpClient client = HttpClients.custom() .setDefaultCredentialsProvider(getCredentialsProvider(url, username, pwd)).build(); int responseCode = 0; StringBuffer respo = null;/*from w w w.j ava 2 s . c o m*/ String userPassword = username + ":" + pwd; // String encoding = Base64.getEncoder().encodeToString(userPassword.getBytes()); String encoding = Base64.encodeBase64String(userPassword.getBytes()); try { HttpGet request = new HttpGet(url); request.addHeader("Authorization", "Basic " + encoding); request.addHeader("User-Agent", USER_AGENT); System.out.println("Executing request " + request.getRequestLine()); CloseableHttpResponse response = client.execute(request); try { responseCode = response.getStatusLine().getStatusCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); respo = new StringBuffer(); String inputLine; while ((inputLine = in.readLine()) != null) { respo.append(inputLine); } } finally { response.close(); } } finally { client.close(); } HTTPResponseData result = new HTTPResponseData(responseCode, ((respo == null) ? "" : respo.toString())); System.out.println(result.getStatusCode() + "/n" + result.getBody()); return result; }