List of usage examples for org.apache.http.client.methods HttpRequestBase releaseConnection
public void releaseConnection()
From source file:com.telefonica.iot.tidoop.apiext.backends.ckan.CKANBackend.java
/** * Common method to perform HTTP requests using the CKAN API with payload. * @param method HTTP method/*from w ww .j a v a2 s. c o m*/ * @param url URL path to be added to the base URL * @param payload Request payload * @return CKANResponse associated to the request * @throws Exception */ public CKANResponse doCKANRequest(String method, String url, String payload) throws Exception { HttpRequestBase request = null; HttpResponse response = null; try { // do the post if (method.equals("GET")) { request = new HttpGet(url); } else if (method.equals("POST")) { HttpPost r = new HttpPost(url); // payload (optional) if (!payload.equals("")) { logger.debug("request payload: " + payload); r.setEntity(new StringEntity(payload, ContentType.create("application/json"))); } // if request = r; } else { throw new Exception("HTTP method not supported: " + method); } // if else // headers request.addHeader("Authorization", apiKey); // execute the request logger.debug("CKAN operation: " + request.toString()); } catch (Exception e) { throw e; } // try catch try { response = httpClientFactory.getHttpClient(ssl).execute(request); } catch (Exception e) { throw new Exception(e.getMessage()); } // try catch try { BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String res = ""; String line; while ((line = reader.readLine()) != null) { res += line; } // while request.releaseConnection(); long l = response.getEntity().getContentLength(); logger.debug("CKAN response (" + l + " bytes): " + response.getStatusLine().toString()); // get the JSON encapsulated in the response logger.debug("response payload: " + res); JSONParser j = new JSONParser(); JSONObject o = (JSONObject) j.parse(res); // return result return new CKANResponse(o, response.getStatusLine().getStatusCode()); } catch (IOException e) { throw e; } catch (IllegalStateException e) { throw e; } catch (ParseException e) { throw e; } // try catch }
From source file:com.linemetrics.monk.api.RestClient.java
private JSONObject request(HttpRequestBase req, Boolean attachAuthHeader) throws RestException, IOException { req.addHeader("Accept", "application/json"); if (creds != null && attachAuthHeader) { creds.authenticate(req);//from w w w . j av a 2 s. c o m } StringBuilder result = new StringBuilder(); try { HttpResponse resp = httpClient.execute(req); HttpEntity ent = resp.getEntity(); if (ent != null) { String encoding = null; if (ent.getContentEncoding() != null) { encoding = ent.getContentEncoding().getValue(); } if (encoding == null) { Header contentTypeHeader = resp.getFirstHeader("content-type"); HeaderElement[] contentTypeElements = contentTypeHeader.getElements(); for (HeaderElement he : contentTypeElements) { NameValuePair nvp = he.getParameterByName("charset"); if (nvp != null) { encoding = nvp.getValue(); } } } InputStreamReader isr = encoding != null ? new InputStreamReader(ent.getContent(), encoding) : new InputStreamReader(ent.getContent()); BufferedReader br = new BufferedReader(isr); String line = ""; while ((line = br.readLine()) != null) result.append(line); } StatusLine sl = resp.getStatusLine(); if (sl.getStatusCode() >= 300) { throw new RestException(sl.getReasonPhrase(), sl.getStatusCode(), result.toString()); } } catch (Exception e) { e.printStackTrace(); throw new RestException(e.getMessage(), -1, ""); } finally { req.releaseConnection(); } return (JSONObject) JSONValue.parse(!result.toString().isEmpty() ? result.toString() : "{\"data\":[]}"); }
From source file:org.neo4j.ogm.drivers.http.request.HttpRequest.java
public static CloseableHttpResponse execute(CloseableHttpClient httpClient, HttpRequestBase request, Credentials credentials) throws HttpRequestException { LOGGER.debug("Thread: {}, request: {}", Thread.currentThread().getId(), request); CloseableHttpResponse response;//w w w . j av a2 s . c om request.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8")); request.setHeader(new BasicHeader(HTTP.USER_AGENT, "neo4j-ogm.java/2.0")); request.setHeader(new BasicHeader("Accept", "application/json;charset=UTF-8")); HttpAuthorization.authorize(request, credentials); // use defaults: 3 retries, 2 second wait between attempts RetryOnExceptionStrategy retryStrategy = new RetryOnExceptionStrategy(); while (retryStrategy.shouldRetry()) { try { response = httpClient.execute(request); StatusLine statusLine = response.getStatusLine(); HttpEntity responseEntity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { String responseText = statusLine.getReasonPhrase(); if (responseEntity != null) { responseText = parseError(EntityUtils.toString(responseEntity)); LOGGER.warn("Thread: {}, response: {}", Thread.currentThread().getId(), responseText); } throw new HttpResponseException(statusLine.getStatusCode(), responseText); } if (responseEntity == null) { throw new ClientProtocolException("Response contains no content"); } return response; // don't close response yet, it is not consumed! } // if we didn't get a response at all, try again catch (NoHttpResponseException nhre) { LOGGER.warn("Thread: {}, No response from server: Retrying in {} milliseconds, retries left: {}", Thread.currentThread().getId(), retryStrategy.getTimeToWait(), retryStrategy.numberOfTriesLeft); retryStrategy.errorOccurred(); } catch (RetryException re) { throw new HttpRequestException(request, re); } catch (ClientProtocolException uhe) { throw new ConnectionException(request.getURI().toString(), uhe); } catch (IOException ioe) { throw new HttpRequestException(request, ioe); } // here we catch any exception we throw above (plus any we didn't throw ourselves), // log the problem, close any connection held by the request // and then rethrow the exception to the caller. catch (Exception exception) { LOGGER.warn("Thread: {}, exception: {}", Thread.currentThread().getId(), exception.getCause().getLocalizedMessage()); request.releaseConnection(); throw exception; } } throw new RuntimeException("Fatal Exception: Should not have occurred!"); }
From source file:org.openmhealth.shim.OAuth1ShimBase.java
@Override @SuppressWarnings("unchecked") public AuthorizationRequestParameters getAuthorizationRequestParameters(String username, Map<String, String> additionalParameters) throws ShimException { String stateKey = OAuth1Utils.generateStateKey(); AccessParameters accessParams = accessParametersRepo.findByUsernameAndShimKey(username, getShimKey(), new Sort(DESC, "dateCreated")); if (accessParams != null && accessParams.getAccessToken() != null) { return AuthorizationRequestParameters.authorized(); }//from ww w.ja v a2 s. c o m HttpRequestBase tokenRequest = null; try { String callbackUrl = shimServerConfig.getCallbackUrl(getShimKey(), stateKey); Map<String, String> requestTokenParameters = new HashMap<>(); requestTokenParameters.put("oauth_callback", callbackUrl); String initiateAuthUrl = getBaseRequestTokenUrl(); tokenRequest = getRequestTokenRequest(initiateAuthUrl, null, null, requestTokenParameters); HttpResponse httpResponse = httpClient.execute(tokenRequest); Map<String, String> tokenParameters = OAuth1Utils.parseRequestTokenResponse(httpResponse); String token = tokenParameters.get(OAuth.OAUTH_TOKEN); String tokenSecret = tokenParameters.get(OAuth.OAUTH_TOKEN_SECRET); if (tokenSecret == null) { throw new ShimException("Request token could not be retrieved"); } URL authorizeUrl = signUrl(getBaseAuthorizeUrl(), token, tokenSecret, null); System.out.println("The authorization url is: "); System.out.println(authorizeUrl); /** * Build the auth parameters entity to return */ AuthorizationRequestParameters parameters = new AuthorizationRequestParameters(); parameters.setUsername(username); parameters.setRedirectUri(callbackUrl); parameters.setStateKey(stateKey); parameters.setAuthorizationUrl(authorizeUrl.toString()); parameters.setRequestParams(tokenParameters); /** * Store the parameters in a repo. */ authorizationRequestParametersRepo.save(parameters); return parameters; } catch (HttpClientErrorException e) { e.printStackTrace(); throw new ShimException("HTTP Error: " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new ShimException("Unable to initiate OAuth1 authorization, could not parse token parameters"); } finally { if (tokenRequest != null) { tokenRequest.releaseConnection(); } } }
From source file:com.logicoy.pdmp.pmpi.http.SimpleWebClient.java
public PMPIHttpClientResponse sendRequest(SessionObject SessionObj, SimpleWebClientSettings settings) { HttpRequestBase httpRequest = null; //HttpPost httpPost = null; //HttpGet httpGet = null; try {/* w w w. ja v a 2 s . c om*/ if (settings.getAction() == SimpleWebClientSettings.ActionType.POST) { httpRequest = new HttpPost(settings.getUri()); } else { httpRequest = new HttpGet(settings.getUri()); } httpRequest.setHeader("Content-Type", settings.getContentType()); httpRequest.setHeader("Allow-Auto-Redirect", String.valueOf(settings.getAutoRedirect())); httpRequest.setHeader("Keep-Alive", String.valueOf(settings.getKeepAlive())); if (settings.getAccept() != null && !settings.getAccept().equals("")) { httpRequest.setHeader("Accept", settings.getAccept()); } if (settings.getMessageBody() != null && !settings.getMessageBody().equals("") && settings.getAction() == SimpleWebClientSettings.ActionType.POST) { byte[] postData = settings.getMessageBody().getBytes(Charset.forName("UTF-8")); StringEntity entity = new StringEntity(settings.getMessageBody(), ContentType.create(settings.getContentType(), Charset.forName("UTF-8"))); ByteArrayOutputStream baos = new ByteArrayOutputStream(); entity.writeTo(baos); HttpPost httpPost = (HttpPost) httpRequest; httpPost.setEntity(entity); } try { httpclient.setCookieStore(SessionObj.getCookieStore()); httpResponse = httpclient.execute(httpRequest); } catch (IOException ioe) { logger.log(Level.SEVERE, "Error while posting data", ioe); throw ioe; } PMPIHttpClientResponse resp = new PMPIHttpClientResponse(); populateResponseObject(httpResponse, resp); System.out .println("Status code returned from server : " + httpResponse.getStatusLine().getStatusCode()); System.out.println("Status resson phrase returned from server : " + httpResponse.getStatusLine().getReasonPhrase()); //EntityUtils.consume(httpResponse.getEntity()); return resp; } catch (Exception e) { ok = false; logger.log(Level.SEVERE, e.getMessage(), e); return null; } finally { if (httpRequest != null) { httpRequest.releaseConnection(); } } }
From source file:com.norconex.collector.http.fetch.impl.GenericDocumentFetcher.java
@Override public CrawlState fetchDocument(HttpClient httpClient, HttpDocument doc) { //TODO replace signature with Writer class. LOG.debug("Fetching document: " + doc.getReference()); HttpRequestBase method = null; try {/*from w w w .j a va2s . c o m*/ method = createUriRequest(doc); // Execute the method. HttpResponse response = httpClient.execute(method); int statusCode = response.getStatusLine().getStatusCode(); InputStream is = response.getEntity().getContent(); if (ArrayUtils.contains(validStatusCodes, statusCode)) { //--- Fetch headers --- Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Header header = headers[i]; String name = header.getName(); if (StringUtils.isNotBlank(headersPrefix)) { name = headersPrefix + name; } if (doc.getMetadata().getString(name) == null) { doc.getMetadata().addString(name, header.getValue()); } } //--- Fetch body doc.setContent(doc.getContent().newInputStream(is)); //read a copy to force caching and then close the HTTP stream IOUtils.copy(doc.getContent(), new NullOutputStream()); return HttpCrawlState.NEW; } if (LOG.isDebugEnabled()) { LOG.debug("Rejected response content: " + IOUtils.toString(is)); IOUtils.closeQuietly(is); } else { // read response anyway to be safer, but ignore content BufferedInputStream bis = new BufferedInputStream(is); int result = bis.read(); while (result != -1) { result = bis.read(); } IOUtils.closeQuietly(bis); } if (statusCode == HttpStatus.SC_NOT_FOUND) { return HttpCrawlState.NOT_FOUND; } LOG.debug("Unsupported HTTP Response: " + response.getStatusLine()); return CrawlState.BAD_STATUS; } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.error("Cannot fetch document: " + doc.getReference() + " (" + e.getMessage() + ")", e); } else { LOG.error("Cannot fetch document: " + doc.getReference() + " (" + e.getMessage() + ")"); } throw new CollectorException(e); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:com.streamreduce.AbstractInContainerTestCase.java
/** * Makes a request to the given url using the given method and possibly submitting * the given data. If you need the request to be an authenticated request, pass in * your authentication token as well./*w ww . j av a 2 s .c om*/ * * @param url the url for the request * @param method the method to use for the request * @param data the data, if any, for the request * @param authnToken the token retrieved during authentication * @param type API or GATEWAY, tells us the auth token key to use * @return the response as string (This is either the response payload or the status code if no payload is sent) * @throws Exception if something goes wrong */ public String makeRequest(String url, String method, Object data, String authnToken, AuthTokenType type) throws Exception { HttpClient httpClient = new DefaultHttpClient(); HttpRequestBase request; String actualPayload; // Set the User-Agent to be safe httpClient.getParams().setParameter(HttpProtocolParams.USER_AGENT, Constants.NODEABLE_HTTP_USER_AGENT); // Create the request object if (method.equals("DELETE")) { request = new HttpDelete(url); } else if (method.equals("GET")) { request = new HttpGet(url); } else if (method.equals("POST")) { request = new HttpPost(url); } else if (method.equals("PUT")) { request = new HttpPut(url); } else if (method.equals("HEAD")) { request = new HttpHead(url); } else { throw new IllegalArgumentException("The method you specified is not supported."); } // Put data into the request for POST and PUT requests if (method.equals("POST") || method.equals("PUT")) { HttpEntityEnclosingRequestBase eeMethod = (HttpEntityEnclosingRequestBase) request; String requestBody = data instanceof JSONObject ? ((JSONObject) data).toString() : new ObjectMapper().writeValueAsString(data); eeMethod.setEntity(new StringEntity(requestBody, MediaType.APPLICATION_JSON, "UTF-8")); } // Add the authentication token to the request if (authnToken != null) { if (type.equals(AuthTokenType.API)) { request.addHeader(Constants.NODEABLE_AUTH_TOKEN, authnToken); } else if (type.equals(AuthTokenType.GATEWAY)) { request.addHeader(Constants.NODEABLE_API_KEY, authnToken); } else { throw new Exception("Unsupported Type of " + type + " for authToken " + authnToken); } } // Execute the request try { HttpResponse response = httpClient.execute(request); String payload = IOUtils.toString(response.getEntity().getContent()); // To work around HEAD, where we cannot receive a payload, and other scenarios where the payload could // be empty, let's stuff the response status code into the response. actualPayload = payload != null && payload.length() > 0 ? payload : Integer.toString(response.getStatusLine().getStatusCode()); } finally { request.releaseConnection(); } return actualPayload; }