Java Code Examples for org.apache.commons.httpclient.HttpMethod#releaseConnection()
The following examples show how to use
org.apache.commons.httpclient.HttpMethod#releaseConnection() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UserMgmtITCase.java From olat with Apache License 2.0 | 6 votes |
@Test public void testGetUsers() throws IOException { final HttpClient c = loginWithCookie("administrator", "olat"); final HttpMethod method = createGet("/users", MediaType.APPLICATION_JSON, true); final int code = c.executeMethod(method); assertEquals(code, 200); final String body = method.getResponseBodyAsString(); method.releaseConnection(); final List<UserVO> vos = parseUserArray(body); final List<Identity> identities = securityManager.getIdentitiesByPowerSearch(null, null, true, null, null, null, null, null, null, null, Identity.STATUS_VISIBLE_LIMIT); assertNotNull(vos); assertFalse(vos.isEmpty()); assertEquals(vos.size(), identities.size()); }
Example 2
Source File: RestClient.java From Kylin with Apache License 2.0 | 6 votes |
public String getKylinProperties() throws IOException { String url = baseUrl + "/admin/config"; HttpMethod request = new GetMethod(url); try { int code = client.executeMethod(request); String msg = Bytes.toString(request.getResponseBody()); JSONObject obj = new JSONObject(msg); msg = obj.getString("config"); if (code != 200) throw new IOException("Invalid response " + code + " with cache wipe url " + url + "\n" + msg); return msg; } catch (JSONException e) { throw new IOException("Error when parsing json response from REST"); } finally { request.releaseConnection(); } }
Example 3
Source File: GroupMgmtITCase.java From olat with Apache License 2.0 | 6 votes |
@Test public void testAddParticipant() throws HttpException, IOException { final HttpClient c = loginWithCookie("administrator", "olat"); final String request = "/groups/" + g1.getKey() + "/participants/" + part3.getKey(); final HttpMethod method = createPut(request, MediaType.APPLICATION_JSON, true); final int code = c.executeMethod(method); method.releaseConnection(); assertTrue(code == 200 || code == 201); final List<Identity> participants = securityManager.getIdentitiesOfSecurityGroup(g1.getPartipiciantGroup()); boolean found = false; for (final Identity participant : participants) { if (participant.getKey().equals(part3.getKey())) { found = true; } } assertTrue(found); }
Example 4
Source File: GroupMgmtITCase.java From olat with Apache License 2.0 | 6 votes |
@Test public void testRemoveTutor() throws HttpException, IOException { final HttpClient c = loginWithCookie("administrator", "olat"); final String request = "/groups/" + g1.getKey() + "/owners/" + owner2.getKey(); final HttpMethod method = createDelete(request, MediaType.APPLICATION_JSON, true); final int code = c.executeMethod(method); method.releaseConnection(); assertTrue(code == 200); final List<Identity> owners = securityManager.getIdentitiesOfSecurityGroup(g1.getOwnerGroup()); boolean found = false; for (final Identity owner : owners) { if (owner.getKey().equals(owner2.getKey())) { found = true; } } assertFalse(found); }
Example 5
Source File: GroupMgmtITCase.java From olat with Apache License 2.0 | 6 votes |
@Test public void testAddTutor() throws HttpException, IOException { final HttpClient c = loginWithCookie("administrator", "olat"); final String request = "/groups/" + g1.getKey() + "/owners/" + owner3.getKey(); final HttpMethod method = createPut(request, MediaType.APPLICATION_JSON, true); final int code = c.executeMethod(method); method.releaseConnection(); assertTrue(code == 200 || code == 201); final List<Identity> owners = securityManager.getIdentitiesOfSecurityGroup(g1.getOwnerGroup()); boolean found = false; for (final Identity owner : owners) { if (owner.getKey().equals(owner3.getKey())) { found = true; } } assertTrue(found); }
Example 6
Source File: UserMgmtITCase.java From olat with Apache License 2.0 | 6 votes |
@Test public void testGetUser() throws IOException { final HttpClient c = loginWithCookie("administrator", "olat"); final HttpMethod method = createGet("/users/" + id1.getKey(), MediaType.APPLICATION_JSON, true); final int code = c.executeMethod(method); assertEquals(code, 200); final String body = method.getResponseBodyAsString(); method.releaseConnection(); final UserVO vo = parse(body, UserVO.class); assertNotNull(vo); assertEquals(vo.getKey(), id1.getKey()); assertEquals(vo.getLogin(), id1.getName()); // are the properties there? assertFalse(vo.getProperties().isEmpty()); }
Example 7
Source File: UserMgmtITCase.java From olat with Apache License 2.0 | 6 votes |
@Test public void testGetUserNotAdmin() throws IOException { final HttpClient c = loginWithCookie("rest-one", "A6B7C8"); final HttpMethod method = createGet("/users/" + id2.getKey(), MediaType.APPLICATION_JSON, true); final int code = c.executeMethod(method); assertEquals(code, 200); final String body = method.getResponseBodyAsString(); method.releaseConnection(); final UserVO vo = parse(body, UserVO.class); assertNotNull(vo); assertEquals(vo.getKey(), id2.getKey()); assertEquals(vo.getLogin(), id2.getName()); // no properties for security reason assertTrue(vo.getProperties().isEmpty()); }
Example 8
Source File: GrafanaDashboardServiceImpl.java From cymbal with Apache License 2.0 | 6 votes |
private void doHttpAPI(HttpMethod method) throws MonitorException { // 拼装http post请求,调用grafana http api建立dashboard HttpClient httpclient = new HttpClient(); httpclient.getParams().setConnectionManagerTimeout(Constant.Http.CONN_TIMEOUT); httpclient.getParams().setSoTimeout(Constant.Http.SO_TIMEOUT); // api key method.setRequestHeader("Authorization", String.format("Bearer %s", grafanaApiKey)); try { int statusCode = httpclient.executeMethod(method); // 若http请求失败 if (statusCode != Constant.Http.STATUS_OK) { String responseBody = method.getResponseBodyAsString(); throw new MonitorException(responseBody); } } catch (Exception e) { if (e instanceof MonitorException) { throw (MonitorException) e; } else { new MonitorException(e); } } finally { method.releaseConnection(); } }
Example 9
Source File: HttpUtils.java From http4e with Apache License 2.0 | 6 votes |
public static void execute( HttpClient client, HttpMethod httpmethod, ResponseReader reader) throws Exception{ try { client.executeMethod(httpmethod); if (reader != null) { reader.read(httpmethod); } } catch (Exception e) { throw e; } finally { httpmethod.releaseConnection(); } }
Example 10
Source File: MailUtils.java From document-management-system with GNU General Public License v2.0 | 6 votes |
/** * User tinyurl service as url shorter Depends on commons-httpclient:commons-httpclient:jar:3.0 because of * org.apache.jackrabbit:jackrabbit-webdav:jar:1.6.4 */ public static String getTinyUrl(String fullUrl) throws HttpException, IOException { HttpClient httpclient = new HttpClient(); // Prepare a request object HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php"); method.setQueryString(new NameValuePair[]{new NameValuePair("url", fullUrl)}); httpclient.executeMethod(method); InputStreamReader isr = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"); StringWriter sw = new StringWriter(); int c; while ((c = isr.read()) != -1) sw.write(c); isr.close(); method.releaseConnection(); return sw.toString(); }
Example 11
Source File: NetworkTools.java From yeti with MIT License | 6 votes |
public static String getHTMLFromUrl(String url) { HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); String response = ""; try { client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { response = method.getResponseBodyAsString(); } } catch (IOException e) { Logger.getLogger("networkTools.getHTMLFromUrl").log(Level.SEVERE, null, e); } finally { method.releaseConnection(); } return response; }
Example 12
Source File: AuthenticatedHttp.java From alfresco-remote-api with GNU Lesser General Public License v3.0 | 5 votes |
public <T extends Object> T executeHttpMethodUnauthenticated(HttpMethod method, HttpRequestCallback<T> callback) { try { // Try executing the method httpProvider.getHttpClient().executeMethod(null, method); if (callback != null) { return callback.onCallSuccess(method); } return null; } catch (Throwable t) { boolean handled = false; // Delegate to callback to handle error. If not available, throw exception if (callback != null) { handled = callback.onError(method, t); } if (!handled) { throw new RuntimeException("Error while executing an un-authenticated HTTP-call (" + method.getPath() + ")", t); } return null; } finally { method.releaseConnection(); } }
Example 13
Source File: HttpRobotConnection.java From incubator-retired-wave with Apache License 2.0 | 5 votes |
/** * Fetches the given URL, given a method ({@code GET} or {@code POST}). * * @param url the URL to be fetched. * @param method the method to fetch the URL, can be {@code GET} or * {@code POST}. * @return the content of the URL. * * @throws RobotConnectionException if there is a problem fetching the URL, * for example, if the response code is not HTTP OK (200). */ private String fetch(String url, HttpMethod method) throws RobotConnectionException { try { int statusCode = httpClient.executeMethod(method); return RobotConnectionUtil.validateAndReadResponse(url, statusCode, method.getResponseBodyAsStream()); } catch (IOException e) { String msg = "Robot fetch http failure: " + url + "."; throw new RobotConnectionException(msg, e); } finally { method.releaseConnection(); } }
Example 14
Source File: SessionScopeTest.java From tomee with Apache License 2.0 | 5 votes |
@Test public void testShouldBeAbleToAccessServletAndEjb() throws Exception { final String sessionUrl = webappUrl.toExternalForm() + "session"; String[] sessionResult = new String[2]; for (int i = 0; i < sessionResult.length; i++) { HttpClient client = new HttpClient(); HttpMethod get = new GetMethod(sessionUrl); String[] contents = new String[2]; try { for (int j = 0; j < contents.length; j++) { int out = client.executeMethod(get); if (out != 200) { throw new RuntimeException("get " + sessionUrl + " returned " + out); } contents[j] = get.getResponseBodyAsString(); } assertEquals(contents[0], contents[1]); } finally { get.releaseConnection(); } sessionResult[i] = contents[0]; } assertNotSame(sessionResult[0], sessionResult[1]); }
Example 15
Source File: Filter5HttpProxy.java From boubei-tss with Apache License 2.0 | 5 votes |
/** * <p> * 请求转向不同同服务器的其他应用 * </p> * @param appServer * @param req * @param response * @throws IOException * @throws BusinessServletException */ private void proxy4ForeignApplication(AppServer appServer, HttpServletResponse response) throws IOException, BusinessServletException { HttpClient client = HttpClientUtil.getHttpClient(appServer); // 创建HttpClient对象 HttpState httpState = client.getState(); /* 设置用户令牌相关Cookie,包括一个token Cookie和一个 sessionId Cookie */ boolean isSecure = Context.getRequestContext().isSecure(); //是否https请求 String currentAppCode = Context.getApplicationContext().getCurrentAppCode(); //当前应用code String domain = appServer.getDomain(); String path = appServer.getPath(); if (Context.isOnline()) { httpState.addCookie(new Cookie(domain, RequestContext.USER_TOKEN, Context.getToken(), path, null, isSecure)); //token = **************** } if (Environment.getSessionId() != null) { httpState.addCookie(new Cookie(domain, currentAppCode, Environment.getSessionId(), path, null, isSecure)); // TSS = JSessionId } HttpMethod httpMethod = HttpClientUtil.getHttpMethod(appServer); // 创建HttpPost对象(等价于一个Post Http Request) try { // 请求 int statusCode = client.executeMethod(httpMethod); if (statusCode == HttpStatus.SC_OK) { // 转发返回信息 transmitResponse(appServer, response, client, httpMethod); } else if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY) || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || (statusCode == HttpStatus.SC_SEE_OTHER) || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) { dealWithRedirect(appServer, response, client, httpMethod); } } finally { httpMethod.releaseConnection(); } }
Example 16
Source File: AuthenticatedHttp.java From alfresco-remote-api with GNU Lesser General Public License v3.0 | 4 votes |
/** * Execute the given method, authenticated as the given user using ticket-based authentication. * @param method method to execute * @param userName name of user to authenticate * @return status-code resulting from the request */ private <T extends Object> T executeWithTicketAuthentication(HttpMethod method, String userName, String password, HttpRequestCallback<T> callback) { String ticket = authDetailProvider.getTicketForUser(userName); if(ticket == null) { ticket = fetchLoginTicket(userName, password); authDetailProvider.updateTicketForUser(userName, ticket); } try { HttpState state = applyTicketToMethod(method, ticket); // Try executing the method int result = httpProvider.getHttpClient().executeMethod(null, method, state); if(result == HttpStatus.SC_UNAUTHORIZED || result == HttpStatus.SC_FORBIDDEN) { method.releaseConnection(); if(!method.validate()) { throw new RuntimeException("Ticket re-authentication failed for user " + userName + " (HTTPMethod not reusable)"); } // Fetch new ticket, store and apply to HttpMethod ticket = fetchLoginTicket(userName, userName); authDetailProvider.updateTicketForUser(userName, ticket); state = applyTicketToMethod(method, ticket); // Run method agian with new ticket result = httpProvider.getHttpClient().executeMethod(null, method, state); } if(callback != null) { return callback.onCallSuccess(method); } return null; } catch(Throwable t) { boolean handled = false; // Delegate to callback to handle error. If not available, throw exception if(callback != null) { handled = callback.onError(method, t); } if(!handled) { throw new RuntimeException("Error while executing HTTP-call (" + method.getPath() +")", t); } return null; } finally { method.releaseConnection(); } }
Example 17
Source File: TunnelComponent.java From olat with Apache License 2.0 | 4 votes |
private void fetchFirstResource(final Identity ident) { final TURequest tureq = new TURequest(); // config, ureq); tureq.setContentType(null); // not used tureq.setMethod("GET"); tureq.setParameterMap(Collections.EMPTY_MAP); tureq.setQueryString(query); if (startUri != null) { if (startUri.startsWith("/")) { tureq.setUri(startUri); } else { tureq.setUri("/" + startUri); } } // if (allowedToSendPersonalHeaders) { final String userName = ident.getName(); final User u = ident.getUser(); final String lastName = getUserService().getUserProperty(u, UserConstants.LASTNAME, loc); final String firstName = getUserService().getUserProperty(u, UserConstants.FIRSTNAME, loc); final String email = getUserService().getUserProperty(u, UserConstants.EMAIL, loc); tureq.setEmail(email); tureq.setFirstName(firstName); tureq.setLastName(lastName); tureq.setUserName(userName); // } final HttpMethod meth = fetch(tureq, httpClientInstance); if (meth == null) { setFetchError(); } else { final Header responseHeader = meth.getResponseHeader("Content-Type"); String mimeType; if (responseHeader == null) { setFetchError(); mimeType = null; } else { mimeType = responseHeader.getValue(); } if (mimeType != null && mimeType.startsWith("text/html")) { // we have html content, let doDispatch handle it for // inline rendering, update hreq for next content request String body; try { body = meth.getResponseBodyAsString(); } catch (final IOException e) { log.warn("Problems when tunneling URL::" + tureq.getUri(), e); htmlContent = "Error: cannot display inline :" + tureq.getUri() + ": Unknown transfer problem '"; return; } final SimpleHtmlParser parser = new SimpleHtmlParser(body); if (!parser.isValidHtml()) { // this is not valid HTML, deliver // asynchronuous } meth.releaseConnection(); htmlHead = parser.getHtmlHead(); jsOnLoad = parser.getJsOnLoad(); htmlContent = parser.getHtmlContent(); } else { htmlContent = "Error: cannot display inline :" + tureq.getUri() + ": mime type was '" + mimeType + "' but expected 'text/html'. Response header was '" + responseHeader + "'."; } } }
Example 18
Source File: AuthenticatedHttp.java From alfresco-remote-api with GNU Lesser General Public License v3.0 | 4 votes |
/** * Execute the given method, authenticated as the given user using Basic Authentication. * @param method method to execute * @param userName name of user to authenticate (note: if null then attempts to run with no authentication - eq. Quick/Shared Link test) * @param callback called after http-call is executed. When callback returns, the * response stream is closed, so all respose-related operations should be done in the callback. Can be null. * @return result returned by the callback or null if no callback is given. */ private <T extends Object> T executeWithBasicAuthentication(HttpMethod method, String userName, String password, HttpRequestCallback<T> callback) { try { HttpState state = new HttpState(); if (userName != null) { state.setCredentials( new AuthScope(null, AuthScope.ANY_PORT), new UsernamePasswordCredentials(userName, password)); } httpProvider.getHttpClient().executeMethod(null, method, state); if(callback != null) { return callback.onCallSuccess(method); } // No callback used, return null return null; } catch(Throwable t) { boolean handled = false; // Delegate to callback to handle error. If not available, throw exception if(callback != null) { handled = callback.onError(method, t); } if(!handled) { throw new RuntimeException("Error while executing HTTP-call (" + method.getPath() +")", t); } return null; } finally { method.releaseConnection(); } }
Example 19
Source File: HostObjectUtils.java From carbon-apimgt with Apache License 2.0 | 4 votes |
public static NativeObject sendHttpHEADRequest(String urlVal, String invalidStatusCodesRegex) { boolean isConnectionError = true; String response = null; NativeObject data = new NativeObject(); //HttpClient client = new DefaultHttpClient(); HttpHead head = new HttpHead(urlVal); //Change implementation to use http client as default http client do not work properly with mutual SSL. org.apache.commons.httpclient.HttpClient clientnew = new org.apache.commons.httpclient.HttpClient(); // extract the host name and add the Host http header for sanity head.addHeader("Host", urlVal.replaceAll("https?://", "").replaceAll("(/.*)?", "")); clientnew.getParams().setParameter("http.socket.timeout", 4000); clientnew.getParams().setParameter("http.connection.timeout", 4000); HttpMethod method = new HeadMethod(urlVal); if (System.getProperty(APIConstants.HTTP_PROXY_HOST) != null && System.getProperty(APIConstants.HTTP_PROXY_PORT) != null) { if (log.isDebugEnabled()) { log.debug("Proxy configured, hence routing through configured proxy"); } String proxyHost = System.getProperty(APIConstants.HTTP_PROXY_HOST); String proxyPort = System.getProperty(APIConstants.HTTP_PROXY_PORT); clientnew.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, Integer.parseInt(proxyPort))); } try { int statusCodeNew = clientnew.executeMethod(method); //Previous implementation // HttpResponse httpResponse = client.execute(head); String statusCode = String.valueOf(statusCodeNew);//String.valueOf(httpResponse.getStatusLine().getStatusCode()); String reasonPhrase = String.valueOf(statusCodeNew);//String.valueOf(httpResponse.getStatusLine().getReasonPhrase()); //If the endpoint doesn't match the regex which specify the invalid status code, it will return success. if (!statusCode.matches(invalidStatusCodesRegex)) { if (log.isDebugEnabled() && statusCode.equals(String.valueOf(HttpStatus.SC_METHOD_NOT_ALLOWED))) { log.debug("Endpoint doesn't support HTTP HEAD"); } response = "success"; isConnectionError = false; } else { //This forms the real backend response to be sent to the client data.put("statusCode", data, statusCode); data.put("reasonPhrase", data, reasonPhrase); response = ""; isConnectionError = false; } } catch (IOException e) { // sending a default error message. log.error("Error occurred while connecting to backend : " + urlVal + ", reason : " + e.getMessage(), e); String[] errorMsg = e.getMessage().split(": "); if (errorMsg.length > 1) { response = errorMsg[errorMsg.length - 1]; //This is to get final readable part of the error message in the exception and send to the client isConnectionError = false; } } finally { method.releaseConnection(); } data.put("response", data, response); data.put("isConnectionError", data, isConnectionError); return data; }
Example 20
Source File: HttpUtil.java From openhab1-addons with Eclipse Public License 2.0 | 4 votes |
/** * Executes the given <code>url</code> with the given <code>httpMethod</code> * * @param httpMethod the HTTP method to use * @param url the url to execute (in milliseconds) * @param httpHeaders optional HTTP headers which has to be set on request * @param content the content to be send to the given <code>url</code> or * <code>null</code> if no content should be send. * @param contentType the content type of the given <code>content</code> * @param timeout the socket timeout to wait for data * @param proxyHost the hostname of the proxy * @param proxyPort the port of the proxy * @param proxyUser the username to authenticate with the proxy * @param proxyPassword the password to authenticate with the proxy * @param nonProxyHosts the hosts that won't be routed through the proxy * @return the response body or <code>NULL</code> when the request went wrong */ public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content, String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser, String proxyPassword, String nonProxyHosts) { HttpClient client = new HttpClient(); // only configure a proxy if a host is provided if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); if (StringUtils.isNotBlank(proxyUser)) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPassword)); } } HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); if (httpHeaders != null) { for (String httpHeaderKey : httpHeaders.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey))); } } // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && content != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType)); } Credentials credentials = extractCredentials(url); if (credentials != null) { client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, credentials); } if (logger.isDebugEnabled()) { try { logger.debug("About to execute '{}'", method.getURI()); } catch (URIException e) { logger.debug("{}", e.getMessage()); } } try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.debug("Method failed: {}", method.getStatusLine()); } String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.debug("{}", responseBody); } return responseBody; } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); } finally { method.releaseConnection(); } return null; }