List of usage examples for org.apache.http.client.methods HttpRequestBase releaseConnection
public void releaseConnection()
From source file:com.telefonica.iot.cygnus.backends.http.HttpBackend.java
/** * Does a Http request given a method, a relative URL, a list of headers and * the payload Protected method due to it's used by the tests. * /*from w w w. j a v a 2 s.c om*/ * @param method * @param url * @param headers * @param entity * @return The result of the request * @throws CygnusRuntimeError * @throws CygnusPersistenceError */ protected JsonResponse doRequest(String method, String url, ArrayList<Header> headers, StringEntity entity) throws CygnusRuntimeError, CygnusPersistenceError { HttpResponse httpRes = null; HttpRequestBase request; switch (method) { case "PUT": HttpPut reqPut = new HttpPut(url); if (entity != null) { reqPut.setEntity(entity); } // if request = reqPut; break; case "POST": HttpPost reqPost = new HttpPost(url); if (entity != null) { reqPost.setEntity(entity); } // if request = reqPost; break; case "GET": request = new HttpGet(url); break; case "DELETE": request = new HttpDelete(url); break; default: throw new CygnusRuntimeError("Http '" + method + "' method not supported"); } // switch if (headers != null) { for (Header header : headers) { request.setHeader(header); } // for } // if LOGGER.debug("Http request: " + request.toString()); try { httpRes = httpClient.execute(request); } catch (IOException e) { request.releaseConnection(); throw new CygnusPersistenceError("Request error", "IOException", e.getMessage()); } // try catch JsonResponse response = createJsonResponse(httpRes); request.releaseConnection(); return response; }
From source file:rawsclient.RawsClient.java
@SuppressWarnings("unchecked") private Map<String, Object> exec_request(HttpRequestBase httpMethod) throws HttpResponseException, IOException, ClassCastException { DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter("http.useragent", this.user_agent_name); BASE64Encoder enc = new sun.misc.BASE64Encoder(); String userpassword = this.username + ":" + this.password; String encodedAuthorization = enc.encode(userpassword.getBytes()); httpMethod.addHeader("Authorization", "Basic " + encodedAuthorization); HttpResponse response = httpClient.execute(httpMethod); if (response.getStatusLine().getStatusCode() > 299) { // try to get the reasons from the json error response String strErr = getReasonsFromErrorMsg(response); if (strErr.isEmpty()) { // if we can't get the reasons, dump the entire response body strErr = inputStreamToString(response.getEntity().getContent()).toString(); }// w w w . j a v a 2s . co m throw new HttpResponseException(response.getStatusLine().getStatusCode(), strErr); } ObjectMapper mapper2 = new ObjectMapper(); Object responseObject = mapper2.readValue(response.getEntity().getContent(), Object.class); httpMethod.releaseConnection(); return (Map<String, Object>) responseObject; }
From source file:com.liferay.jsonwebserviceclient.JSONWebServiceClientImpl.java
protected String execute(HttpRequestBase httpRequestBase) throws CredentialException, IOException { HttpHost httpHost = new HttpHost(_hostName, _hostPort, _protocol); try {//from ww w. java 2 s . c om if (_closeableHttpClient == null) { afterPropertiesSet(); } HttpResponse httpResponse = _closeableHttpClient.execute(httpHost, httpRequestBase); StatusLine statusLine = httpResponse.getStatusLine(); if (statusLine.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) { if (_logger.isWarnEnabled()) { _logger.warn("Status code " + statusLine.getStatusCode()); } return null; } else if (statusLine.getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) { throw new CredentialException("Not authorized to access JSON web service"); } else if (statusLine.getStatusCode() == HttpServletResponse.SC_SERVICE_UNAVAILABLE) { throw new JSONWebServiceUnavailableException("Service unavailable"); } return EntityUtils.toString(httpResponse.getEntity(), Charsets.UTF_8); } finally { httpRequestBase.releaseConnection(); } }
From source file:com.myjeeva.digitalocean.impl.DigitalOceanClient.java
private String executeHttpRequest(HttpRequestBase request) throws DigitalOceanException, RequestUnsuccessfulException { String response = ""; try {/*from w w w . j a v a 2 s .c o m*/ HttpResponse httpResponse = httpClient.execute(request); LOG.debug("HTTP Response Object:: " + httpResponse); response = appendRateLimitValues(evaluateResponse(httpResponse), httpResponse); LOG.debug("Parsed Response:: " + response); } catch (ClientProtocolException cpe) { throw new RequestUnsuccessfulException(cpe.getMessage(), cpe); } catch (IOException ioe) { throw new RequestUnsuccessfulException(ioe.getMessage(), ioe); } finally { request.releaseConnection(); } return response; }
From source file:mobi.jenkinsci.ci.JenkinsCIPlugin.java
@Override public RawBinaryNode download(final HttpServletRequest req, final String url, final Account account, final PluginConfig pluginConf) throws IOException { final JenkinsClient client = JenkinsClient.getInstance(account, pluginConf); final HttpRequestBase get = getNewHttpRequest(req, url); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final RawBinaryNode result = new RawBinaryNode(); try {/*w w w .jav a 2s . co m*/ final HttpResponse response = client.http.execute(get); final StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpURLConnection.HTTP_OK) { throw new IOException("HTTP-" + get.getMethod() + " " + url + " failed: status code " + status); } IOUtils.copy(response.getEntity().getContent(), out); for (final Header h : response.getAllHeaders()) { final String headerName = h.getName(); if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_TYPE)) { result.setHttpContentType(h.getValue()); } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) { result.setSize(Long.parseLong(h.getValue())); } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_ENCODING)) { result.setHttpCharacterEncoding(h.getValue()); } } } finally { get.releaseConnection(); } result.setData(new ByteArrayInputStream(out.toByteArray())); return result; }
From source file:com.pennassurancesoftware.tutum.client.TutumClient.java
private String executeHttpRequest(HttpRequestBase request) throws TutumException, RequestUnsuccessfulException { String response = ""; try {//from w w w. ja v a 2 s. c o m final HttpResponse httpResponse = httpClient.execute(request); LOG.debug("HTTP Response Object:: " + httpResponse); response = evaluateResponse(request, httpResponse); LOG.debug("Parsed Response:: " + response); } catch (ClientProtocolException cpe) { throw new RequestUnsuccessfulException(cpe.getMessage(), cpe); } catch (IOException ioe) { throw new RequestUnsuccessfulException(ioe.getMessage(), ioe); } finally { request.releaseConnection(); } return response; }
From source file:es.tid.fiware.fiwareconnectors.cygnus.backends.ckan.CKANRequester.java
/** * Common method to perform HTTP request using the CKAN API with payload. * @param method HTTP method//from ww w. j av a 2 s . com * @param urlPath 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 urlPath, String payload) throws Exception { // build the final URL String url = baseURL + urlPath; 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 CygnusRuntimeError("HTTP method not supported: " + method); } // if else // headers request.addHeader("Authorization", apiKey); // execute the request logger.debug("CKAN operation: " + request.toString()); } catch (Exception e) { if (e instanceof CygnusRuntimeError || e instanceof CygnusPersistenceError || e instanceof CygnusBadConfiguration) { throw e; } else { throw new CygnusRuntimeError(e.getMessage()); } // if else } // try catch try { response = httpClient.execute(request); } catch (Exception e) { throw new CygnusPersistenceError(e.getMessage()); } // try catch try { BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String res = reader.readLine(); 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 (Exception e) { if (e instanceof CygnusRuntimeError || e instanceof CygnusPersistenceError || e instanceof CygnusBadConfiguration) { throw e; } else { throw new CygnusRuntimeError(e.getMessage()); } // if else } // try catch }
From source file:com.telefonica.iot.cosmos.hive.authprovider.OAuth2AuthenticationProviderImpl.java
@Override public void Authenticate(String user, String token) throws AuthenticationException { // create the Http client HttpClient httpClient = httpClientFactory.getHttpClient(true); // create the request String url = idmEndpoint + "/user?access_token=" + token; HttpRequestBase request = new HttpGet(url); // do the request HttpResponse httpRes = null;/*w ww .jav a 2s .c o m*/ try { httpRes = httpClient.execute(request); LOGGER.debug("Doing request: " + request.toString()); } catch (IOException e) { throw new AuthenticationException(e.getMessage()); } // try catch // get the input streamResponse String streamResponse = ""; try { BufferedReader reader = new BufferedReader(new InputStreamReader(httpRes.getEntity().getContent())); streamResponse = reader.readLine(); LOGGER.debug("Response received: " + streamResponse); } catch (IOException e) { throw new AuthenticationException(e.getMessage()); } // try catch // parse the input streamResponse as a Json JSONObject jsonResponse = null; try { JSONParser jsonParser = new JSONParser(); jsonResponse = (JSONObject) jsonParser.parse(streamResponse); } catch (ParseException e) { throw new AuthenticationException(e.getMessage()); } // try catch // check if the given token does not exist if (jsonResponse.containsKey("error")) { throw new AuthenticationException("The given token does not exist"); } // if // check if the obtained user id matches the given user if (jsonResponse.containsKey("id") && !jsonResponse.get("id").equals(user)) { throw new AuthenticationException("The given token does not match the given user"); } // if // release the connection request.releaseConnection(); LOGGER.debug("User " + user + " authenticated"); }
From source file:org.craftercms.engine.http.impl.HttpProxyImpl.java
protected void proxyRequest(String url, boolean isGet, HttpServletRequest request, HttpServletResponse response) throws HttpProxyException { String targetUrl = createTargetUrl(url, request); HttpRequestBase httpRequest = null; CloseableHttpResponse httpResponse = null; try {/* w ww. j a va2 s.c o m*/ if (isGet) { httpRequest = createGetRequest(targetUrl, request); } else { httpRequest = createPostRequest(targetUrl, request); } if (logger.isDebugEnabled()) { logger.debug("Proxying to " + getRequestDescription(httpRequest)); } httpResponse = httpClient.execute(httpRequest); response.setStatus(httpResponse.getStatusLine().getStatusCode()); String responseBody = IOUtils.toString(httpResponse.getEntity().getContent()); if (httpResponse.getStatusLine().getStatusCode() >= 400 && logger.isDebugEnabled()) { logger.debug("Received error response from " + getRequestDescription(httpRequest) + ": status = " + httpResponse.getStatusLine().getReasonPhrase() + ", response body = \n" + responseBody); } copyActualResponseHeaders(httpRequest, response); copyActualResponseBody(responseBody, response); } catch (Exception e) { String errorMsg; if (httpRequest != null) { errorMsg = "Error while proxying to " + getRequestDescription(httpRequest); } else { errorMsg = "Error while proxing to " + (isGet ? "GET[" : "POST[") + targetUrl + "]"; } logger.error(errorMsg, e); throw new HttpProxyException(errorMsg, e); } finally { if (httpRequest != null) { httpRequest.releaseConnection(); } } }