List of usage examples for org.apache.commons.httpclient HttpClient executeMethod
public int executeMethod(HttpMethod paramHttpMethod) throws IOException, HttpException
From source file:be.fedict.trust.service.util.ClockDriftUtil.java
public static Date executeTSP(ClockDriftConfigEntity clockDriftConfig, NetworkConfig networkConfig) throws IOException, TSPException { LOG.debug("clock drift detection: " + clockDriftConfig.toString()); TimeStampRequestGenerator requestGen = new TimeStampRequestGenerator(); TimeStampRequest request = requestGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100)); byte[] requestData = request.getEncoded(); HttpClient httpClient = new HttpClient(); if (null != networkConfig) { httpClient.getHostConfiguration().setProxy(networkConfig.getProxyHost(), networkConfig.getProxyPort()); }/*from ww w . j a v a2 s . c o m*/ PostMethod postMethod = new PostMethod(clockDriftConfig.getServer()); postMethod.setRequestEntity(new ByteArrayRequestEntity(requestData, "application/timestamp-query")); int statusCode = httpClient.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { throw new TSPException("Error contacting TSP server " + clockDriftConfig.getServer()); } TimeStampResponse tspResponse = new TimeStampResponse(postMethod.getResponseBodyAsStream()); postMethod.releaseConnection(); return tspResponse.getTimeStampToken().getTimeStampInfo().getGenTime(); }
From source file:com.oneapm.base.tools.UrlPostMethod.java
public static void urlPostMethod(String url, String json) { HttpClient httpClient = new HttpClient(); PostMethod method = new PostMethod(url); try {// w ww. ja v a 2 s. com if (json != null && !json.trim().equals("")) { RequestEntity requestEntity = new StringRequestEntity(json, "application/x-www-form-urlencoded", "utf-8"); method.setRequestEntity(requestEntity); } long startTime = System.currentTimeMillis(); int x = httpClient.executeMethod(method); long elapsedTime = System.currentTimeMillis(); System.out.println(x + ":" + (elapsedTime - startTime)); } catch (IOException e) { e.printStackTrace(); } finally { method.releaseConnection(); } }
From source file:edu.stanford.muse.email.WebPageThumbnail.java
/** create a dataset and emit top level pages */ public static void fetchWebPageThumbnails(String rootDir, String prefix, List<Document> allDocs, boolean archivedPages, int limit) throws IOException, JSONException { List<LinkInfo> links = EmailUtils.getLinksForDocs(allDocs); // compute map of url -> doc Map<String, List<Document>> fmap = new LinkedHashMap<String, List<Document>>(); for (LinkInfo li : links) { List<Document> lis = fmap.get(li); if (lis == null) { lis = new ArrayList<Document>(); fmap.put(li.link, lis);/* www. ja va2 s . c o m*/ } lis.add(li.doc); } List<Blob> allDatas = new ArrayList<Blob>(); BlobStore data_store = new BlobStore(rootDir + File.separator + "blobs"); int successes = 0; outer: for (String url : fmap.keySet()) { List<Document> lis = fmap.get(url); for (Document doc : lis) { if (doc instanceof DatedDocument) { String targetURL = url; DatedDocument dd = ((DatedDocument) doc); if (archivedPages) { Calendar c = new GregorianCalendar(); c.setTime(((DatedDocument) doc).date); String archiveDate = c.get(Calendar.YEAR) + String.format("%02d", c.get(Calendar.MONTH)) + String.format("%02d", c.get(Calendar.DATE)) + "120000"; // color dates targetURL = "http://web.archive.org/" + archiveDate + "/" + url; } try { // the name is just the URL, so that different URLs have a different Data String sanitizedURL = Util.sanitizeFolderName(targetURL); // targetURL is not really a folder name, but all we want is to convert the '/' to __ WebPageThumbnail wpt = new WebPageThumbnail(sanitizedURL + ".png", dd); /// 10K as a dummy ?? boolean targetURLIsHTML = !(Util.is_image_filename(targetURL) || Util.is_office_document(targetURL) || Util.is_pdf_filename(targetURL)); if (!data_store.contains(wpt)) { // download the html page first HttpClient client = new HttpClient(); String tmpFile = File.createTempFile("webtn.", ".tmp").getAbsolutePath(); GetMethod get = new GetMethod(targetURL); int statusCode = client.executeMethod(get); if (statusCode == 200) { // execute method and handle any error responses. InputStream in = get.getResponseBodyAsStream(); // Process the data from the input stream. Util.copy_stream_to_file(in, tmpFile); get.releaseConnection(); if (targetURLIsHTML) { // use jtidy to convert it to xhtml String tmpXHTMLFile = File.createTempFile("webtn.", ".xhtml").getAbsolutePath(); Tidy tidy = new Tidy(); // obtain a new Tidy instance tidy.setXHTML(true); // set desired config options using tidy setters InputStream is = new FileInputStream(tmpFile); OutputStream os = new FileOutputStream(tmpXHTMLFile); tidy.parse(is, os); // run tidy, providing an input and output stream try { is.close(); } catch (Exception e) { } try { os.close(); } catch (Exception e) { } // use xhtmlrenderer to convert it to a png File pngFile = File.createTempFile("webtn.", ".png"); BufferedImage buff = null; String xhtmlURL = new File(tmpXHTMLFile).toURI().toString(); buff = Graphics2DRenderer.renderToImage(xhtmlURL, 640, 480); ImageIO.write(buff, "png", pngFile); data_store.add(wpt, new FileInputStream(pngFile)); } else { data_store.add(wpt, new FileInputStream(tmpFile)); if (Util.is_pdf_filename(targetURL)) data_store.generate_thumbnail(wpt); } successes++; if (successes == limit) break outer; } else log.info("Unable to GET targetURL " + targetURL + " status code = " + statusCode); } allDatas.add(wpt); } catch (Exception e) { log.warn(Util.stackTrace(e)); } catch (Error e) { log.warn(Util.stackTrace(e)); } } if (!archivedPages) break; // only need to show one page if we're not showing archives } } BlobSet bs = new BlobSet(rootDir, allDatas, data_store); bs.generate_top_level_page(prefix); }
From source file:com.ibm.hrl.proton.adapters.rest.client.RestClient.java
/** * Gets a list of events from the specified producer. * The producer is specified by the URL (which includes all the relevant info - the web * server name, port name, web service name and the URI path * The content type can be either application/xml,application/json or plain text * The content type will be specified by the specific producer, and a formatter * will be supplied to create an event instance from the type * /* w ww .j a v a2 s. c o m*/ * The method returns a list of String instances representing the event instances, * which will be parsed by the specific input adapter according to the producer's configuration * @param url * @return * @throws RESTException */ protected static List<String> getEventsFromProducer(HttpClient httpClient, GetMethod getMethod, String url, String contentType) throws RESTException { List<String> resultEvents = new ArrayList<String>(); // Execute request try { int result = httpClient.executeMethod(getMethod); if (result != 200) { throw new RESTException( "Could not perform GET on producer " + url + ", responce result: " + result); } InputStream input = getMethod.getResponseBodyAsStream(); BufferedReader br = new BufferedReader(new InputStreamReader(input)); String output; while ((output = br.readLine()) != null) { resultEvents.add(output); } } catch (Exception e) { throw new RESTException(e); } return resultEvents; }
From source file:com.comcast.cats.service.util.HttpClientUtil.java
public static synchronized Object getForObject(String uri, Map<String, String> paramMap) { Object responseObject = new Object(); HttpMethod httpMethod = new GetMethod(uri); if ((null != paramMap) && (!paramMap.isEmpty())) { httpMethod.setQueryString(getNameValuePair(paramMap)); }/*from w w w . j av a2s.c om*/ Yaml yaml = new Yaml(); HttpClient client = new HttpClient(); InputStream responseStream = null; Reader inputStreamReader = null; try { int responseCode = client.executeMethod(httpMethod); if (HttpStatus.SC_OK != responseCode) { logger.error("[ REQUEST ] " + httpMethod.getURI().toString()); logger.error("[ METHOD ] " + httpMethod.getName()); logger.error("[ STATUS ] " + responseCode); } else { logger.trace("[ REQUEST ] " + httpMethod.getURI().toString()); logger.trace("[ METHOD ] " + httpMethod.getName()); logger.trace("[ STATUS ] " + responseCode); } responseStream = httpMethod.getResponseBodyAsStream(); inputStreamReader = new InputStreamReader(responseStream, VideoRecorderServiceConstants.UTF); responseObject = yaml.load(inputStreamReader); } catch (IOException ioException) { ioException.printStackTrace(); } finally { cleanUp(inputStreamReader, responseStream, httpMethod); } return responseObject; }
From source file:com.comcast.cats.service.util.HttpClientUtil.java
public static synchronized Object postForObject(String uri, Map<String, String> paramMap) { Object responseObject = new Object(); HttpMethod httpMethod = new PostMethod(uri); if ((null != paramMap) && (!paramMap.isEmpty())) { httpMethod.setQueryString(getNameValuePair(paramMap)); }//from w ww . jav a2 s . com Yaml yaml = new Yaml(); HttpClient client = new HttpClient(); InputStream responseStream = null; Reader inputStreamReader = null; try { int responseCode = client.executeMethod(httpMethod); if (HttpStatus.SC_OK != responseCode) { logger.error("[ REQUEST ] " + httpMethod.getURI().toString()); logger.error("[ METHOD ] " + httpMethod.getName()); logger.error("[ STATUS ] " + responseCode); } else { logger.trace("[ REQUEST ] " + httpMethod.getURI().toString()); logger.trace("[ METHOD ] " + httpMethod.getName()); logger.trace("[ STATUS ] " + responseCode); } responseStream = httpMethod.getResponseBodyAsStream(); inputStreamReader = new InputStreamReader(responseStream, VideoRecorderServiceConstants.UTF); responseObject = yaml.load(inputStreamReader); } catch (IOException ioException) { ioException.printStackTrace(); } finally { cleanUp(inputStreamReader, responseStream, httpMethod); } return responseObject; }
From source file:com.comcast.cats.service.util.HttpClientUtil.java
public static synchronized Object deleteForObject(String uri, Map<String, String> paramMap) { Object responseObject = new Object(); HttpMethod httpMethod = new DeleteMethod(uri); if ((null != paramMap) && (!paramMap.isEmpty())) { httpMethod.setQueryString(getNameValuePair(paramMap)); }//from w w w . j a v a 2 s .com Yaml yaml = new Yaml(); HttpClient client = new HttpClient(); InputStream responseStream = null; Reader inputStreamReader = null; try { int responseCode = client.executeMethod(httpMethod); if (HttpStatus.SC_OK != responseCode) { logger.error("[ REQUEST ] " + httpMethod.getURI().toString()); logger.error("[ METHOD ] " + httpMethod.getName()); logger.error("[ STATUS ] " + responseCode); } else { logger.trace("[ REQUEST ] " + httpMethod.getURI().toString()); logger.trace("[ METHOD ] " + httpMethod.getName()); logger.trace("[ STATUS ] " + responseCode); } responseStream = httpMethod.getResponseBodyAsStream(); inputStreamReader = new InputStreamReader(responseStream, VideoRecorderServiceConstants.UTF); responseObject = yaml.load(inputStreamReader); } catch (IOException ioException) { ioException.printStackTrace(); } finally { cleanUp(inputStreamReader, responseStream, httpMethod); } return responseObject; }
From source file:edu.du.penrose.systems.fedoraProxy.web.bus.ProxyController.java
/** * Call the HttpMethod and write all results and status to the HTTP response * object.//from ww w.j ava 2 s .co m * * THIS IS THE REQUEST WE NEED TO DUPLICATE GET * /fedora/get/codu:72/ECTD_test_1_access.pdf HTTP/1.1 Host: localhost:8080 * Connection: keep-alive Accept: * application/xml,application/xhtml+xml,text/ * html;q=0.9,text/plain;q=0.8,image/png,*;q=0.5 User-Agent: Mozilla/5.0 * (X11; U; Linux x86_64; en-US) AppleWebKit/534.10 (KHTML, like Gecko) * Chrome/8.0.552.215 Safari/534.10 Accept-Encoding: gzip,deflate,sdch * Accept-Language: en-US,en;q=0.8 Accept-Charset: * ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: fez_list=YjowOw%3D%3D * * ACTUAL SENT GET /fedora/get/codu:72/ECTD_test_1_access.pdf HTTP/1.1 * Accept: * application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q * =0.8,image/png,*;q=0.5 Connection: keep-alive Accept-Encoding: * gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: * ISO-8859-1,utf-8;q=0.7,*;q=0.3 : User-Agent: Jakarta * Commons-HttpClient/3.1 Host: localhost:8080 * * @param proxyCommand * @param response * @param authenicate true to set Preemptive authentication */ public static void executeMethod(String proxyCommand, HttpServletResponse response, boolean authenicate) { HttpClient theClient = new HttpClient(); HttpMethod method = new GetMethod(proxyCommand); setDefaultHeaders(method); setAdrCredentials(theClient, authenicate); try { theClient.executeMethod(method); response.setStatus(method.getStatusCode()); // Set the content type, as it comes from the server Header[] headers = method.getResponseHeaders(); for (Header header : headers) { if ("Content-Type".equalsIgnoreCase(header.getName())) { response.setContentType(header.getValue()); } /** * Copy all headers, except Transfer-Encoding which is getting set * set elsewhere. At this point response.containsHeader( * "Transfer-Encoding" ) is false, however it is getting set twice * according to wireshark, therefore we do not set it here. */ if (!header.getName().equalsIgnoreCase("Transfer-Encoding")) { response.setHeader(header.getName(), header.getValue()); } } // Write the body, flush and close InputStream is = method.getResponseBodyAsStream(); BufferedInputStream bis = new BufferedInputStream(is); StringBuffer sb = new StringBuffer(); byte[] bytes = new byte[8192]; // reading as chunk of 8192 bytes int count = bis.read(bytes); while (count != -1 && count <= 8192) { response.getOutputStream().write(bytes, 0, count); count = bis.read(bytes); } bis.close(); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e) { logger.error(e.getMessage()); } finally { method.releaseConnection(); } }
From source file:edu.stanford.epad.epadws.xnat.XNATDeletionOperations.java
public static int deleteXNATDICOMStudy(String xnatProjectLabelOrID, String xnatSubjectLabelOrID, String studyUID, String sessionID) { String xnatStudyDeleteURL = XNATUtil.buildXNATDICOMStudyDeletionURL(xnatProjectLabelOrID, xnatSubjectLabelOrID, studyUID); HttpClient client = new HttpClient(); DeleteMethod method = new DeleteMethod(xnatStudyDeleteURL); int xnatStatusCode; method.setRequestHeader("Cookie", "JSESSIONID=" + sessionID); try {/*from ww w . j a v a 2 s. c o m*/ log.info("Invoking XNAT with URL " + xnatStudyDeleteURL); xnatStatusCode = client.executeMethod(method); if (unexpectedDeletionStatusCode(xnatStatusCode)) log.warning("Failure calling XNAT to delete Study; status code = " + xnatStatusCode); else { eventTracker.recordStudyEvent(sessionID, xnatProjectLabelOrID, xnatSubjectLabelOrID, studyUID); } } catch (IOException e) { log.warning("Error calling XNAT to delete study + " + studyUID + " for patient " + xnatSubjectLabelOrID + " from project " + xnatProjectLabelOrID, e); xnatStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } finally { method.releaseConnection(); } return xnatStatusCode; }
From source file:fr.cls.atoll.motu.library.misc.cas.HttpClientTutorial.java
public static void test() { HttpClient client = new HttpClient(); client.getParams().setParameter("http.useragent", "Test Client"); client.getParams().setParameter("http.connection.timeout", new Integer(5000)); GetMethod method = new GetMethod(); FileOutputStream fos = null;//from w ww . j av a2s.com try { method.setURI(new URI("http://www.google.com", true)); int returnCode = client.executeMethod(method); if (returnCode != HttpStatus.SC_OK) { System.err.println("Unable to fetch default page, status code: " + returnCode); } System.err.println(method.getResponseBodyAsString()); method.setURI(new URI("http://www.google.com/images/logo.gif", true)); returnCode = client.executeMethod(method); if (returnCode != HttpStatus.SC_OK) { System.err.println("Unable to fetch image, status code: " + returnCode); } byte[] imageData = method.getResponseBody(); fos = new FileOutputStream(new File("google.gif")); fos.write(imageData); HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost("www.yahoo.com", null, 80, Protocol.getProtocol("http")); method.setURI(new URI("/", true)); client.executeMethod(hostConfig, method); System.err.println(method.getResponseBodyAsString()); } catch (HttpException he) { System.err.println(he); } catch (IOException ie) { System.err.println(ie); } finally { method.releaseConnection(); if (fos != null) { try { fos.close(); } catch (Exception fe) { } } } }