List of usage examples for org.apache.http.client.methods CloseableHttpResponse getEntity
HttpEntity getEntity();
From source file:tradeok.HttpTool.java
@SuppressWarnings("deprecation") public static String invokeGet(String url, Map<String, String> params, String encode, int connectTimeout) throws Exception { String responseString = null; RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(connectTimeout) .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectTimeout) .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build(); StringBuilder sb = new StringBuilder(); sb.append(url);//from www .j av a2 s . c o m int i = 0; if (params != null) { for (Entry<String, String> entry : params.entrySet()) { if (i == 0 && !url.contains("?")) { sb.append("?"); } else { sb.append("&"); } sb.append(entry.getKey()); sb.append("="); String value = entry.getValue(); try { sb.append(URLEncoder.encode(value, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); System.out.printf("\nwarn:encode http get params error, value is " + value, e); sb.append(URLEncoder.encode(value)); } i++; } } // System.out.printf("\ninfo:[HttpUtils Get] begin invoke:" // + sb.toString()); HttpGet get = new HttpGet(sb.toString()); get.setConfig(requestConfig); get.setHeader("Connection", "keep-alive"); try { CloseableHttpResponse response = httpclient.execute(get); try { HttpEntity entity = response.getEntity(); try { if (entity != null) { responseString = EntityUtils.toString(entity, encode); } } finally { if (entity != null) { entity.getContent().close(); } } } finally { if (response != null) { response.close(); } } } finally { get.releaseConnection(); } return responseString; }
From source file:org.sead.repositories.reference.util.SEADGoogleLogin.java
static void getTokenFromRefreshToken() { access_token = null;/* w ww . j a va2 s . c o m*/ expires_in = -1; token_start_time = -1; if (gProps == null) { initGProps(); } /* Try refresh token */ // Query for token now that user has gone through browser part // of // flow // The method used in getTokensFromCode should work here as well - I // think URL encoded Form is the recommended way... HttpPost post = new HttpPost(gProps.token_uri); post.addHeader("accept", "application/json"); post.addHeader("Content-Type", "application/x-www-form-urlencoded"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4); nameValuePairs.add(new BasicNameValuePair("client_id", gProps.client_id)); nameValuePairs.add(new BasicNameValuePair("client_secret", gProps.client_secret)); nameValuePairs.add(new BasicNameValuePair("refresh_token", refresh_token)); nameValuePairs.add(new BasicNameValuePair("grant_type", "refresh_token")); try { post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = null; try { try { response = httpclient.execute(post); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { String responseJSON = EntityUtils.toString(resEntity); ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON); access_token = root.get("access_token").asText(); // refresh_token = // root.get("refresh_token").asText(); token_start_time = System.currentTimeMillis() / 1000; expires_in = root.get("expires_in").asInt(); } } else { log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase()); HttpEntity resEntity = response.getEntity(); } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { log.error("Error obtaining access token: " + e.getMessage()); } finally { if (response != null) { response.close(); } httpclient.close(); } } catch (IOException io) { log.error("Error closing connections: " + io.getMessage()); } }
From source file:utils.APIExporter.java
/** * This method will get the summary of API documentation * @param accessToken access token with scope view * @param uuid uuid of the API/*from www. j ava2 s .c o m*/ * @return String output of documentation summary */ private static String getAPIDocumentation(String accessToken, String uuid) { ApiImportExportConfiguration config = ApiImportExportConfiguration.getInstance(); try { //REST API call on Get API Documents String url = config.getPublisherUrl() + "apis/" + uuid + "/documents"; CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate()); //HttpClients.createDefault(); HttpGet request = new HttpGet(url); request.setHeader(HttpHeaders.AUTHORIZATION, ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken); CloseableHttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); return EntityUtils.toString(entity, ImportExportConstants.CHARSET); } catch (IOException e) { log.error("Error occurred while getting API documents"); } return null; }
From source file:org.cloudsimulator.utility.RestAPI.java
public static ResponseMessageByteArray receiveByteArray(final String restAPIURI, final String username, final String password, final String typeOfByteArray) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse = null; ResponseMessageByteArray responseMessageByteArray = null; httpResponse = getRequestBasicAuth(httpClient, escapeURI(restAPIURI), username, password, typeOfByteArray); if (httpResponse != null) { if (httpResponse.getStatusLine() != null) { if (httpResponse.getEntity() != null) { responseMessageByteArray = new ResponseMessageByteArray( httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), IOUtils.toByteArray(httpResponse.getEntity().getContent())); } else { responseMessageByteArray = new ResponseMessageByteArray( httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), null); }//from ww w . j av a 2 s. c om } else { if (httpResponse.getEntity() != null) { responseMessageByteArray = new ResponseMessageByteArray(null, null, IOUtils.toByteArray(httpResponse.getEntity().getContent())); } } httpResponse.close(); } httpClient.close(); return responseMessageByteArray; }
From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java
/** * Do get.//w w w . j a v a 2 s . c om * * @param uri * the uri * @param headers * the headers * @return the string * @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 doGet(String uri, HashMap<String, String> headers) throws ClientProtocolException, IOException, HttpResponseException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGetSimpleResp resp = new HttpGetSimpleResp(); try { HttpGet httpGet = new HttpGet(uri); for (String key : headers.keySet()) { httpGet.addHeader(key, headers.get(key)); } CloseableHttpResponse response = httpclient.execute(httpGet); resp.setStatusCode(response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { try { HttpEntity entity = response.getEntity(); if (entity != null) { // TODO to use for performance in the future // ResponseHandler<String> handler = new BasicResponseHandler(); 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:com.magnet.tools.tests.RestStepDefs.java
@When("^I send the following Rest queries:$") public static void sendRestQueries(List<RestQueryEntry> entries) throws Throwable { for (RestQueryEntry e : entries) { String url = expandVariables(e.url); StatusLine statusLine;/*from www .ja v a 2 s.c om*/ HttpUriRequest httpRequest; HttpEntity entityResponse; CloseableHttpClient httpClient = getTestHttpClient(new URI(url)); Object body = isStringNotEmpty(e.body) ? e.body : getRef(e.bodyRef); String verb = e.verb; if ("GET".equalsIgnoreCase(verb)) { httpRequest = new HttpGet(url); } else if ("POST".equalsIgnoreCase(verb)) { httpRequest = new HttpPost(url); ((HttpPost) httpRequest).setEntity(new StringEntity(expandVariables((String) body))); } else if ("PUT".equalsIgnoreCase(verb)) { httpRequest = new HttpPut(url); ((HttpPut) httpRequest).setEntity(new StringEntity(expandVariables((String) body))); } else if ("DELETE".equalsIgnoreCase(verb)) { httpRequest = new HttpDelete(url); } else { throw new IllegalArgumentException("Unknown verb: " + e.verb); } String response; setHttpHeaders(httpRequest, e); ScenarioUtils.log("Sending HTTP Request: " + e.url); CloseableHttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpRequest); statusLine = httpResponse.getStatusLine(); entityResponse = httpResponse.getEntity(); InputStream is = entityResponse.getContent(); response = IOUtils.toString(is); EntityUtils.consume(entityResponse); } finally { if (null != httpResponse) { try { httpResponse.close(); } catch (Exception ex) { /* do nothing */ } } } ScenarioUtils.log("====> Received response body:\n " + response); Assert.assertNotNull(response); setHttpResponseBody(response); if (isStringNotEmpty(e.expectedResponseBody)) { // inline the assertion check on http response body ensureHttpResponseBody(e.expectedResponseBody); } if (isStringNotEmpty(e.expectedResponseBodyRef)) { // inline the assertion check on http response body ensureHttpResponseBody((String) getRef(e.expectedResponseBodyRef)); } if (isStringNotEmpty(e.expectedResponseContains)) { // inline the assertion check on http response body ensureHttpResponseBodyContains(e.expectedResponseContains); } if (null == statusLine) { throw new IllegalArgumentException("Status line in http response is null, request was " + e.url); } int statusCode = statusLine.getStatusCode(); ScenarioUtils.log("====> Received response code: " + statusCode); setHttpResponseStatus(statusCode); if (isStringNotEmpty(e.expectedResponseStatus)) { // inline the assertion check on http status ensureHttpResponseStatus(Integer.parseInt(e.expectedResponseStatus)); } } }
From source file:com.beginner.core.utils.HttpUtil.java
/** * <p>To request the GET way.</p> * //from w w w. j a v a 2 s . co m * @param url request URI * @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 get(String url, 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; CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse = null; String result = null; try { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).build(); HttpGet httpGet = new HttpGet(url); httpGet.setConfig(requestConfig); httpResponse = httpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); result = EntityUtils.toString(entity); EntityUtils.consume(entity); } catch (Exception e) { logger.error("GET?", e); return null; } finally { if (null != httpResponse) httpResponse.close(); if (null != httpClient) httpClient.close(); } return result; }
From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java
/** * Do delete./* w ww .j a v a 2s .c om*/ * * @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:utils.APIExporter.java
/** * This method get the API thumbnail and write in to the zip file * @param uuid API id of the API/*from ww w . j a v a2 s.co m*/ * @param accessToken valide access token with view scope * @param APIFolderpath archive base path */ private static void exportAPIThumbnail(String uuid, String accessToken, String APIFolderpath) { ApiImportExportConfiguration config = ApiImportExportConfiguration.getInstance(); try { //REST API call to get API thumbnail String url = config.getPublisherUrl() + "apis/" + uuid + "/thumbnail"; CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate()); HttpGet request = new HttpGet(url); request.setHeader(HttpHeaders.AUTHORIZATION, ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken); CloseableHttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); //assigning the response in to inputStream BufferedHttpEntity httpEntity = new BufferedHttpEntity(entity); InputStream imageStream = httpEntity.getContent(); byte[] byteArray = IOUtils.toByteArray(imageStream); InputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(byteArray)); //getting the mime type of the input Stream String mimeType = URLConnection.guessContentTypeFromStream(inputStream); //getting file extension String extension = getThumbnailFileType(mimeType); OutputStream outputStream = null; if (extension != null) { //writing image in to the archive try { outputStream = new FileOutputStream(APIFolderpath + File.separator + "icon." + extension); IOUtils.copy(httpEntity.getContent(), outputStream); } finally { IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(imageStream); IOUtils.closeQuietly(inputStream); } } } catch (IOException e) { log.error("Error occurred while exporting the API thumbnail"); } }
From source file:com.aws.sampleImage.url.LambdaFunctionImageURLCrawlerHandler.java
private static String callFlickrAPIForEachKeyword(String query, String synsetCode) throws IOException, JSONException { String apiKey = "ad4f88ecfd53b17f93178e19703fe00d"; String apiSecret = "96cab0e9f89468d6"; int totalPages = 4; int total = 500; int perPage = 500; int counter = 0;//For monitoring purposes only int currentCount = 0; for (int i = 1; i <= totalPages && currentCount <= total; i++, currentCount = currentCount + perPage) { StringBuffer sb = new StringBuffer(512); sb.append("https://api.flickr.com/services/rest/?method=flickr.photos.search&text=").append(query) .append("&extras=url_c,url_m,url_n,license,owner_name&per_page=500&page=").append(i) .append("&format=json&api_key=").append(apiKey).append("&api_secret=").append(apiSecret) .append("&license=4,5,6,7,8"); String url = sb.toString(); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); CloseableHttpResponse httpResponse = httpClient.execute(httpGet); //System.out.println("GET Response Status:: " + httpResponse.getStatusLine().getStatusCode()); BufferedReader reader = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent())); String inputLine;/* w w w . jav a2 s .c o m*/ StringBuffer response = new StringBuffer(); while ((inputLine = reader.readLine()) != null) { response.append(inputLine); } reader.close(); String responseString = response.toString(); responseString = responseString.replace("jsonFlickrApi(", ""); int length = responseString.length(); responseString = responseString.substring(0, length - 1); // print result httpClient.close(); JSONObject json = null; try { json = new JSONObject(responseString); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println("Converted JSON String " + json); JSONObject photosObj = json.has("photos") ? json.getJSONObject("photos") : null; total = photosObj.has("total") ? (Integer.parseInt(photosObj.getString("total"))) : 0; perPage = photosObj.has("perpage") ? (Integer.parseInt(photosObj.getString("perpage"))) : 0; //System.out.println(" perPage --> " + perPage + " total --> " + total); JSONArray photoArr = photosObj.getJSONArray("photo"); //System.out.println("Length of Array --> " + photoArr.length()); String scrapedImageURL = ""; for (int itr = 0; itr < photoArr.length(); itr++) { JSONObject tempObject = photoArr.getJSONObject(itr); scrapedImageURL = tempObject.has("url_c") ? tempObject.getString("url_c") : tempObject.has("url_m") ? tempObject.getString("url_m") : tempObject.has("url_n") ? tempObject.getString("url_n") : ""; //System.out.println("Scraped Image URL, need to insert this to Amazon DYnamo DB --> " + scrapedImageURL); counter++; insertScrapedImageURLsInDynamoDB(scrapedImageURL, synsetCode, query); } } System.out.println("C O U N T E R -> " + counter); return null; }