List of usage examples for org.apache.commons.httpclient.methods GetMethod GetMethod
public GetMethod(String uri)
From source file:att.jaxrs.client.Tag.java
public static TagCollection getTags() { GetMethod get = new GetMethod(Constants.SELECT_ALL_TAG_OPERATION); TagCollection tag = new TagCollection(); HttpClient httpClient = new HttpClient(); try {/*from w w w.j a va 2 s .c o m*/ int result = httpClient.executeMethod(get); System.out.println(Constants.RESPONSE_STATUS_CODE + result); tag = Marshal.unmarshal(TagCollection.class, get.getResponseBodyAsStream()); } catch (IOException e) { e.printStackTrace(); } finally { get.releaseConnection(); } return tag; }
From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.services.SettingsLoaderImpl.java
public RemoteSettings getConfiguration(String eid, String sessionId, String basePath, String csrfNonce) throws SettingsLoaderException { try {//from w ww . j a va2 s. c o m logger.debug("Attempting to load Settings for '" + eid + "'"); GetMethod method = new GetMethod( basePath + "/hqu/tomcatserverconfig/tomcatserverconfig/getConfiguration.hqu"); configureMethod(method, eid, sessionId, csrfNonce); httpClient.executeMethod(method); if (method.getStatusCode() >= 300 && method.getStatusCode() < 400) { logger.info("Unable to load Settings for '" + eid + "', HQ session expired"); throw new SettingsLoaderException(SESSION_EXPIRED_MESSAGE); } else if (method.getStatusCode() >= 400) { logger.warn("Unable to load Settings for '" + eid + "', " + method.getStatusCode() + " " + method.getStatusText()); throw new SettingsLoaderException(method.getStatusText()); } Settings settings = (Settings) xstream.fromXML(method.getResponseBodyAsString()); RemoteSettings remoteSettings = new RemoteSettings(); remoteSettings.setSettings(settings); remoteSettings.setBasePath(basePath); remoteSettings.setSessionId(sessionId); remoteSettings.setCsrfNonce(csrfNonce); logger.info("Loaded Settings for '" + eid + "'"); return remoteSettings; } catch (SSLHandshakeException e) { logger.error("Server SSL certificate is untrusted: " + e.getMessage(), e); throw new SettingsLoaderException( "Unable to load settings because the server is using an untrusted SSL certificate. " + "Please check the documentation for more information.", e); } catch (IOException e) { logger.error("Unable to load Settings for '" + eid + "': " + e.getMessage(), e); throw new SettingsLoaderException( "Unable to load settings because of a server error, please check the logs for more details", e); } }
From source file:it.geosolutions.geoserver.rest.HTTPUtils.java
/** * Performs an HTTP GET on the given URL. <BR> * Basic auth is used if both username and pw are not null. * /*from w w w . j a v a2 s .c o m*/ * @param url The URL where to connect to. * @param username Basic auth credential. No basic auth if null. * @param pw Basic auth credential. No basic auth if null. * @return The HTTP response as a String if the HTTP response code was 200 * (OK). * @throws MalformedURLException */ public static String get(String url, String username, String pw) { GetMethod httpMethod = null; HttpClient client = new HttpClient(); HttpConnectionManager connectionManager = client.getHttpConnectionManager(); try { setAuth(client, url, username, pw); httpMethod = new GetMethod(url); connectionManager.getParams().setConnectionTimeout(5000); int status = client.executeMethod(httpMethod); if (status == HttpStatus.SC_OK) { InputStream is = httpMethod.getResponseBodyAsStream(); String response = IOUtils.toString(is); IOUtils.closeQuietly(is); if (response.trim().length() == 0) { // sometime gs rest fails LOGGER.warn("ResponseBody is empty"); return null; } else { return response; } } else { LOGGER.info("(" + status + ") " + HttpStatus.getStatusText(status) + " -- " + url); } } catch (ConnectException e) { LOGGER.info("Couldn't connect to [" + url + "]"); } catch (IOException e) { LOGGER.info("Error talking to [" + url + "]", e); } finally { if (httpMethod != null) httpMethod.releaseConnection(); connectionManager.closeIdleConnections(0); } return null; }
From source file:com.honnix.cheater.network.CheaterHttpClient.java
public boolean heartbeat() { GetMethod getMethod = new GetMethod(CheaterConstant.HEARTBEAT_URL); boolean result = execute(getMethod); if (result) { for (Validator validator : validatorList) { result = validator.isHeartbeatValid(httpClient, getMethod); }//w w w . j a v a 2s .co m } getMethod.releaseConnection(); return result; }
From source file:jetbrains.buildServer.importJenkins.web.JenkinsImportController.java
@Override protected void doPost(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Element xmlResponse) { final String jenkinsConfURL = request.getParameter("jenkinsConfUrl"); final String projectName = request.getParameter("projectName"); HttpClient httpClient = HttpUtil.createHttpClient(120); // 2 minutes final GetMethod get = new GetMethod(jenkinsConfURL); try {//from w w w . j a va2 s .c o m httpClient.executeMethod(get); final Element rootElem = FileUtil.parseDocument(get.getResponseBodyAsStream(), false); JenkinsImport.importProject(projectName, rootElem, myMyProjectManager); } catch (IOException e) { e.printStackTrace(); } catch (JDOMException e) { e.printStackTrace(); } }
From source file:com.google.apphosting.vmruntime.jetty9.VmRuntimeJettySessionTest.java
public void testSsl_WithSSL() throws Exception { HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); URL url = createUrl("/test-ssl"); GetMethod get = new GetMethod(url.toString()); get.addRequestHeader(VmApiProxyEnvironment.HTTPS_HEADER, "on"); int httpCode = httpClient.executeMethod(get); assertEquals(200, httpCode);/*from www.j a v a2s . co m*/ assertEquals("true:https:https://localhost/test-ssl", get.getResponseBodyAsString()); }
From source file:exception.handler.authorization.UnhandledAuthorizationExceptionTest.java
@Test public void authorizationException() throws HttpException, IOException { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(deploymentUrl + "/error.jsf"); int status = client.executeMethod(method); assertEquals(SC_UNAUTHORIZED, status); }
From source file:fr.openwide.talendalfresco.rest.client.RestAuthenticationTest.java
public void testRestLogin() { // create client and configure it HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout); // instantiating a new method and configuring it GetMethod method = new GetMethod(restCommandUrlPrefix + "login"); method.setFollowRedirects(true); // ? // Provide custom retry handler is necessary (?) method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); NameValuePair[] params = new NameValuePair[] { new NameValuePair("username", "admin"), new NameValuePair("password", "admin") }; method.setQueryString(params);/*from w w w.j a va 2 s . c o m*/ try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } // Read the response body. byte[] responseBody = method.getResponseBody(); System.out.println(new String(responseBody)); // TODO rm HashSet<String> defaultElementSet = new HashSet<String>( Arrays.asList(new String[] { RestConstants.TAG_COMMAND, RestConstants.TAG_CODE, RestConstants.TAG_CONTENT, RestConstants.TAG_ERROR, RestConstants.TAG_MESSAGE })); HashMap<String, String> elementValueMap = new HashMap<String, String>(6); try { XMLEventReader xmlReader = XmlHelper.getXMLInputFactory() .createXMLEventReader(new ByteArrayInputStream(responseBody)); StringBuffer singleLevelTextBuf = null; while (xmlReader.hasNext()) { XMLEvent event = xmlReader.nextEvent(); switch (event.getEventType()) { case XMLEvent.CHARACTERS: case XMLEvent.CDATA: if (singleLevelTextBuf != null) { singleLevelTextBuf.append(event.asCharacters().getData()); } // else element not meaningful break; case XMLEvent.START_ELEMENT: StartElement startElement = event.asStartElement(); String elementName = startElement.getName().getLocalPart(); if (defaultElementSet.contains(elementName) // TODO another command specific level || "ticket".equals(elementName)) { // reinit buffer at start of meaningful elements singleLevelTextBuf = new StringBuffer(); } else { singleLevelTextBuf = null; // not useful } break; case XMLEvent.END_ELEMENT: if (singleLevelTextBuf == null) { break; // element not meaningful } // TODO or merely put it in the map since the element has been tested at start EndElement endElement = event.asEndElement(); elementName = endElement.getName().getLocalPart(); if (defaultElementSet.contains(elementName)) { String value = singleLevelTextBuf.toString(); elementValueMap.put(elementName, value); // TODO test if it is code and it is not OK, break to error handling } // TODO another command specific level else if ("ticket".equals(elementName)) { ticket = singleLevelTextBuf.toString(); } // singleLevelTextBuf = new StringBuffer(); // no ! in start break; } } } catch (XMLStreamException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Throwable t) { // TODO Auto-generated catch block t.printStackTrace(); //throw t; } String code = elementValueMap.get(RestConstants.TAG_CODE); assertTrue(RestConstants.CODE_OK.equals(code)); System.out.println("got ticket " + ticket); } catch (HttpException e) { // TODO e.printStackTrace(); } catch (IOException e) { // TODO e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } }
From source file:com.owncloud.android.lib.common.accounts.ExternalLinksOperation.java
@Override protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; int status = -1; GetMethod get = null;//from w ww . j av a 2 s. c o m String ocsUrl = client.getBaseUri() + OCS_ROUTE_EXTERNAL_LINKS; try { // check capabilities RemoteOperation getCapabilities = new GetRemoteCapabilitiesOperation(); RemoteOperationResult capabilitiesResult = getCapabilities.execute(client); OCCapability capability = (OCCapability) capabilitiesResult.getData().get(0); if (capability.getExternalLinks().isTrue()) { get = new GetMethod(ocsUrl); get.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); get.setQueryString(new NameValuePair[] { new NameValuePair("format", "json") }); status = client.executeMethod(get); if (isSuccess(status)) { String response = get.getResponseBodyAsString(); Log_OC.d(TAG, "Successful response: " + response); // parse JSONArray links = new JSONObject(response).getJSONObject(NODE_OCS).getJSONArray(NODE_DATA); ArrayList<Object> resultLinks = new ArrayList<>(); for (int i = 0; i < links.length(); i++) { JSONObject link = links.getJSONObject(i); if (link != null) { Integer id = link.getInt(NODE_ID); String iconUrl = link.getString(NODE_ICON); String language = ""; if (link.has(NODE_LANGUAGE)) { language = link.getString(NODE_LANGUAGE); } ExternalLinkType type; switch (link.getString(NODE_TYPE)) { case "link": type = ExternalLinkType.LINK; break; case "settings": type = ExternalLinkType.SETTINGS; break; case "quota": type = ExternalLinkType.QUOTA; break; default: type = ExternalLinkType.UNKNOWN; break; } String name = link.getString(NODE_NAME); String url = link.getString(NODE_URL); boolean redirect = false; if (link.has(NODE_REDIRECT)) { redirect = link.getInt(NODE_REDIRECT) == 1; } resultLinks.add(new ExternalLink(id, iconUrl, language, type, name, url, redirect)); } } result = new RemoteOperationResult(true, status, get.getResponseHeaders()); result.setData(resultLinks); } else { result = new RemoteOperationResult(false, status, get.getResponseHeaders()); String response = get.getResponseBodyAsString(); Log_OC.e(TAG, "Failed response while getting external links "); if (response != null) { Log_OC.e(TAG, "*** status code: " + status + " ; response message: " + response); } else { Log_OC.e(TAG, "*** status code: " + status); } } } else { result = new RemoteOperationResult(RemoteOperationResult.ResultCode.NOT_AVAILABLE); Log_OC.d(TAG, "External links disabled"); } } catch (Exception e) { result = new RemoteOperationResult(e); Log_OC.e(TAG, "Exception while getting external links ", e); } finally { if (get != null) { get.releaseConnection(); } } return result; }
From source file:com.cerema.cloud2.lib.resources.status.GetRemoteStatusOperation.java
private boolean tryConnection(OwnCloudClient client) { boolean retval = false; GetMethod get = null;//ww w . j a v a 2s .c om String baseUrlSt = client.getBaseUri().toString(); try { get = new GetMethod(baseUrlSt + AccountUtils.STATUS_PATH); HttpParams params = get.getParams().getDefaultParams(); params.setParameter(HttpMethodParams.USER_AGENT, OwnCloudClientManagerFactory.getUserAgent()); get.getParams().setDefaults(params); client.setFollowRedirects(false); boolean isRedirectToNonSecureConnection = false; int status = client.executeMethod(get, TRY_CONNECTION_TIMEOUT, TRY_CONNECTION_TIMEOUT); mLatestResult = new RemoteOperationResult((status == HttpStatus.SC_OK), status, get.getResponseHeaders()); String redirectedLocation = mLatestResult.getRedirectedLocation(); while (redirectedLocation != null && redirectedLocation.length() > 0 && !mLatestResult.isSuccess()) { isRedirectToNonSecureConnection |= (baseUrlSt.startsWith("https://") && redirectedLocation.startsWith("http://")); get.releaseConnection(); get = new GetMethod(redirectedLocation); status = client.executeMethod(get, TRY_CONNECTION_TIMEOUT, TRY_CONNECTION_TIMEOUT); mLatestResult = new RemoteOperationResult((status == HttpStatus.SC_OK), status, get.getResponseHeaders()); redirectedLocation = mLatestResult.getRedirectedLocation(); } String response = get.getResponseBodyAsString(); if (status == HttpStatus.SC_OK) { JSONObject json = new JSONObject(response); if (!json.getBoolean(NODE_INSTALLED)) { mLatestResult = new RemoteOperationResult( RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED); } else { String version = json.getString(NODE_VERSION); OwnCloudVersion ocVersion = new OwnCloudVersion(version); if (!ocVersion.isVersionValid()) { mLatestResult = new RemoteOperationResult(RemoteOperationResult.ResultCode.BAD_OC_VERSION); } else { // success if (isRedirectToNonSecureConnection) { mLatestResult = new RemoteOperationResult( RemoteOperationResult.ResultCode.OK_REDIRECT_TO_NON_SECURE_CONNECTION); } else { mLatestResult = new RemoteOperationResult( baseUrlSt.startsWith("https://") ? RemoteOperationResult.ResultCode.OK_SSL : RemoteOperationResult.ResultCode.OK_NO_SSL); } ArrayList<Object> data = new ArrayList<Object>(); data.add(ocVersion); mLatestResult.setData(data); retval = true; } } } else { mLatestResult = new RemoteOperationResult(false, status, get.getResponseHeaders()); } } catch (JSONException e) { mLatestResult = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED); } catch (Exception e) { mLatestResult = new RemoteOperationResult(e); } finally { if (get != null) get.releaseConnection(); } if (mLatestResult.isSuccess()) { Log_OC.i(TAG, "Connection check at " + baseUrlSt + ": " + mLatestResult.getLogMessage()); } else if (mLatestResult.getException() != null) { Log_OC.e(TAG, "Connection check at " + baseUrlSt + ": " + mLatestResult.getLogMessage(), mLatestResult.getException()); } else { Log_OC.e(TAG, "Connection check at " + baseUrlSt + ": " + mLatestResult.getLogMessage()); } return retval; }