List of usage examples for org.apache.commons.httpclient.methods GetMethod GetMethod
public GetMethod(String uri)
From source file:davmail.util.ClientCertificateTest.java
public void testConnect() throws IOException { GetMethod getMethod = new GetMethod("/testdir"); httpClient.executeMethod(getMethod); assertEquals(HttpStatus.SC_OK, getMethod.getStatusCode()); System.out.println(getMethod.getResponseBodyAsString()); }
From source file:com.cerema.cloud2.lib.resources.shares.GetRemoteSharesForFileOperation.java
@Override protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; int status = -1; GetMethod get = null;/* w ww .j ava 2 s.co m*/ try { // Get Method get = new GetMethod(client.getBaseUri() + ShareUtils.SHARING_API_PATH); // Add Parameters to Get Method get.setQueryString(new NameValuePair[] { new NameValuePair(PARAM_PATH, mRemoteFilePath), new NameValuePair(PARAM_RESHARES, String.valueOf(mReshares)), new NameValuePair(PARAM_SUBFILES, String.valueOf(mSubfiles)) }); get.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); status = client.executeMethod(get); if (isSuccess(status)) { String response = get.getResponseBodyAsString(); // Parse xml response and obtain the list of shares ShareToRemoteOperationResultParser parser = new ShareToRemoteOperationResultParser( new ShareXMLParser()); parser.setOwnCloudVersion(client.getOwnCloudVersion()); parser.setServerBaseUri(client.getBaseUri()); result = parser.parse(response); if (result.isSuccess()) { Log_OC.d(TAG, "Got " + result.getData().size() + " shares"); } } else { result = new RemoteOperationResult(false, status, get.getResponseHeaders()); } } catch (Exception e) { result = new RemoteOperationResult(e); Log_OC.e(TAG, "Exception while getting shares", e); } finally { if (get != null) { get.releaseConnection(); } } return result; }
From source file:gr.upatras.ece.nam.fci.panlab.RepoClient.java
/** * Make a GET call towards the repository. The BASIC Authentication is handled automatically * @param tgwaddr// w w w .ja va 2 s . c o m */ public void execute(String tgwaddr) { String reqRepoURL = repoHostAddress + tgwaddr; HttpClient client = new HttpClient(); // pass our credentials to HttpClient, they will only be used for // authenticating to servers with realm "realm" on the host // "www.verisign.com", to authenticate against an arbitrary realm // or host change the appropriate argument to null. client.getState().setCredentials(new AuthScope(null, 8080), new UsernamePasswordCredentials(username, password)); // create a GET method that reads a file over HTTPS, // we're assuming that this file requires basic // authentication using the realm above. GetMethod get = new GetMethod(reqRepoURL); System.out.println("Request: " + reqRepoURL); get.setRequestHeader("User-Agent", "RepoM2M-1.00"); //get.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Tell the GET method to automatically handle authentication. The // method will use any appropriate credentials to handle basic // authentication requests. Setting this value to false will cause // any request for authentication to return with a status of 401. // It will then be up to the client to handle the authentication. get.setDoAuthentication(true); try { // execute the GET client.executeMethod(get); // print the status and response InputStream responseBody = get.getResponseBodyAsStream(); CopyInputStream cis = new CopyInputStream(responseBody); response_stream = cis.getCopy(); System.out.println("Response body=" + "\n" + convertStreamToString(response_stream)); response_stream.reset(); //return theinputstream; } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // release any connection resources used by the method get.releaseConnection(); } //return null; }
From source file:edu.wisc.my.portlets.bookmarks.domain.CollectionFolder.java
/** * Returns an immutable sorted view of the values of the children Map. The sorting is done * using the current childComparator. Warning, this is has a time cost of 2n log(n) * on every call./*from w w w .ja v a 2 s . c o m*/ * * @return An immutable sorted view of the folder's children. */ public List<Entry> getSortedChildren() { List<Entry> children = new ArrayList<Entry>(); log.debug("children: " + children.size()); HttpClient client = new HttpClient(); GetMethod get = null; try { log.debug("getting url " + url); get = new GetMethod(url); int rc = client.executeMethod(get); if (rc != HttpStatus.SC_OK) { log.error("HttpStatus:" + rc); } DocumentBuilderFactory domBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = domBuilderFactory.newDocumentBuilder(); InputStream in = get.getResponseBodyAsStream(); builder = domBuilderFactory.newDocumentBuilder(); Document doc = builder.parse(in); get.releaseConnection(); Element e = (Element) doc.getElementsByTagName("rdf:RDF").item(0); log.debug("got root " + e); NodeList n = e.getElementsByTagName("item"); log.debug("found items " + n.getLength()); for (int i = 0; i < n.getLength(); i++) { Bookmark bookmark = new Bookmark(); Element l = (Element) n.item(i); bookmark.setName(((Element) l.getElementsByTagName("title").item(0)).getTextContent()); bookmark.setUrl(((Element) l.getElementsByTagName("link").item(0)).getTextContent()); if (l.getElementsByTagName("description").getLength() > 0) { bookmark.setNote(((Element) l.getElementsByTagName("description").item(0)).getTextContent()); } children.add(bookmark); log.debug("added bookmark " + bookmark.getName() + " " + bookmark.getUrl()); } } catch (HttpException e) { log.error("Error parsing delicious", e); } catch (IOException e) { log.error("Error parsing delicious", e); } catch (ParserConfigurationException e) { log.error("Error parsing delicious", e); } catch (SAXException e) { log.error("Error parsing delicious", e); } finally { if (get != null) get.releaseConnection(); } log.debug("children: " + children.size()); return children; }
From source file:com.netsteadfast.greenstep.sys.CxfServerBean.java
@SuppressWarnings("unchecked") public static Map<String, Object> shutdownOrReloadCallOneSystem(HttpServletRequest request, String system, String type) throws ServiceException, Exception { if (StringUtils.isBlank(system) || StringUtils.isBlank(type)) { throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK)); }//from w w w . j a va 2 s. c o m String urlStr = ApplicationSiteUtils.getBasePath(system, request) + "config-services?type=" + type + "&value=" + createParamValue(); logger.info("shutdownOrReloadCallSystem , url=" + urlStr); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(urlStr); client.executeMethod(method); byte[] responseBody = method.getResponseBody(); if (null == responseBody) { throw new Exception("no response!"); } String content = new String(responseBody, Constants.BASE_ENCODING); logger.info("shutdownOrReloadCallSystem , system=" + system + " , type=" + type + " , response=" + content); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> dataMap = null; try { dataMap = (Map<String, Object>) mapper.readValue(content, HashMap.class); } catch (JsonParseException e) { logger.error(e.getMessage().toString()); } catch (JsonMappingException e) { logger.error(e.getMessage().toString()); } if (null == dataMap) { throw new Exception("response content error!"); } return dataMap; }
From source file:com.kagilum.intellij.icescrum.IceScrumRepository.java
@Override public CancellableConnection createCancellableConnection() { extractSettings(getUrl());/*from w ww .jav a 2 s . c o m*/ GetMethod method = new GetMethod(createCompleteUrl()); return new HttpTestConnection<GetMethod>(method) { @Override public void doTest(GetMethod method) throws Exception { if (!isConfigured()) { throw new IOException("Setting missing..."); } method.setRequestHeader("Content-type", "text/json"); HttpClient client = getHttpClient(); client.executeMethod(method); int statusCode = method.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { checkServerStatus(statusCode); } Task[] results = getIssues(null, 1, 0); if (results.length < 1) throw new IOException("No results fetched, sure this is correct settings?"); } }; }
From source file:com.mikenimer.familydam.web.jobs.FacebookLikesJob.java
@Override protected JobResult queryFacebook(Node facebookData, String username, String userPath, String nextUrl) throws RepositoryException, IOException, JSONException { String accessToken = facebookData.getProperty("accessToken").getString(); String expiresIn = facebookData.getProperty("expiresIn").getString(); String signedRequest = facebookData.getProperty("signedRequest").getString(); String userId = "me"; if (facebookData.hasProperty("userId")) { userId = facebookData.getProperty("userId").getString(); }// w ww .j a v a 2 s . c o m String _url = nextUrl; if (nextUrl == null) { _url = "https://graph.facebook.com/" + userId + "/likes?access_token=" + accessToken; } URL url = new URL(_url); HttpClient client = new HttpClient(); GetMethod method = new GetMethod(_url); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { return JobResult.FAILED; } // Read the response body. String jsonStr = method.getResponseBodyAsString(); return saveData(username, jsonStr, FACEBOOKPATH, "like"); }
From source file:com.inbravo.scribe.rest.service.crm.zh.auth.basic.ZHBasicAuthManager.java
@Override public final String getSessionId(final String userId, final String password, final String crmURL, final String crmProtocol) throws Exception { logger.debug("----Inside getSessionId, userId: " + userId + " & password: " + password + " & crmURL: " + crmURL + " & crmProtocol: " + crmProtocol); /* Validate protocol */ if (crmProtocol == null || "".equalsIgnoreCase(crmProtocol)) { /* Send user error */ throw new ScribeException( ScribeResponseCodes._1003 + "Invalid protocol to communicate with Zoho: " + crmProtocol); }//from www . j a v a 2 s . co m String loginURL = crmURL; /* Change CRM service URL to CRM login URL */ if (crmURL.toLowerCase().startsWith("crm")) { /* If CRM URL contains . */ if (crmURL.toLowerCase().contains(".")) { /* Split the URL */ final String[] loginURLArr = crmURL.split("\\."); /* Create login URL */ loginURL = "accounts." + loginURLArr[1] + "." + loginURLArr[2]; } } /* Create CRM URL */ final String zohoCRMURL = crmProtocol + "://" + loginURL + "/apiauthtoken/nb/create?SCOPE=ZohoCRM/crmapi&EMAIL_ID=" + userId + "&PASSWORD=" + password; logger.debug("----Inside getSessionId zohoCRMURL: " + zohoCRMURL); /* Get CRM session id */ final GetMethod getMethod = new GetMethod(zohoCRMURL); /* Create new http client instance */ final HttpClient httpclient = new HttpClient(); try { /* Execute get command */ int result = httpclient.executeMethod(getMethod); logger.debug("----Inside getSessionId, response code: " + result + " & body: " + getMethod.getResponseBodyAsString()); /* Check for authentication */ if (result == HttpStatus.SC_UNAUTHORIZED) { logger.debug("----Inside getSessionId found unauthorized user"); throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zoho CRM"); } else { /* Response string */ final String response = getMethod.getResponseBodyAsString(); /* If vailid Zoho CRM response */ if (response != null && response.contains("RESULT=TRUE")) { final String sessionId = response.substring(response.indexOf("=") + 1, response.lastIndexOf("=") - 6); logger.debug("----Inside getSessionId, sessionId: " + sessionId); return sessionId; } else { final String reason = response.substring(response.indexOf("=") + 1, response.lastIndexOf("=") - 6); throw new ScribeException(ScribeResponseCodes._1022 + "No session id is found in response from Zoho CRM : " + reason); } } } catch (final IOException exception) { throw new ScribeException( ScribeResponseCodes._1022 + "Communication error while communicating with Zoho CRM", exception); } finally { /* Release connection socket */ if (getMethod != null) { getMethod.releaseConnection(); } } }
From source file:be.fedict.trust.crl.OnlineCrlRepository.java
private X509CRL getCrl(URI crlUri) throws IOException, CertificateException, CRLException, NoSuchProviderException, NoSuchParserException, StreamParsingException { HttpClient httpClient = new HttpClient(); if (null != this.networkConfig) { httpClient.getHostConfiguration().setProxy(this.networkConfig.getProxyHost(), this.networkConfig.getProxyPort()); }/*from ww w . j a v a2s . c o m*/ if (null != this.credentials) { HttpState httpState = httpClient.getState(); this.credentials.init(httpState); } String downloadUrl = crlUri.toURL().toString(); LOG.debug("downloading CRL from: " + downloadUrl); GetMethod getMethod = new GetMethod(downloadUrl); getMethod.addRequestHeader("User-Agent", "jTrust CRL Client"); int statusCode = httpClient.executeMethod(getMethod); if (HttpURLConnection.HTTP_OK != statusCode) { LOG.debug("HTTP status code: " + statusCode); return null; } CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC"); X509CRL crl = (X509CRL) certificateFactory.generateCRL(getMethod.getResponseBodyAsStream()); LOG.debug("CRL size: " + crl.getEncoded().length + " bytes"); return crl; }
From source file:com.mikenimer.familydam.web.jobs.FacebookPhotosJob.java
@Override protected JobResult queryFacebook(Node facebookData, String username, String userPath, String nextUrl) throws RepositoryException, IOException, JSONException { String accessToken = facebookData.getProperty("accessToken").getString(); String expiresIn = facebookData.getProperty("expiresIn").getString(); String signedRequest = facebookData.getProperty("signedRequest").getString(); String userId = "me"; if (facebookData.hasProperty("userId")) { userId = facebookData.getProperty("userId").getString(); }//from w w w . ja va 2 s. c o m String _url = nextUrl; if (nextUrl == null) { _url = "https://graph.facebook.com/" + userId + "/photos?access_token=" + accessToken; } URL url = new URL(_url); HttpClient client = new HttpClient(); GetMethod method = new GetMethod(_url); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { return JobResult.FAILED; } // Read the response body. String jsonStr = method.getResponseBodyAsString(); return saveData(username, jsonStr, FACEBOOKPATH, "photo"); }