List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream
public abstract InputStream getResponseBodyAsStream() throws IOException;
From source file:edu.utah.further.core.ws.HttpUtil.java
/** * Static method for retrieving the response from an already executed method. This * method does not responsible for closing the inputstream unless an exception occurs * during retrieval of the response.//from ww w. j ava2 s.c om * * @param method * @return */ public static InputStream getHttpResponseStream(final HttpMethod method) { isTrue(method.hasBeenUsed()); Exception exception = null; try { return method.getResponseBodyAsStream(); } catch (final IOException e) { exception = e; throw new ApplicationException("An exception occured while retrieving the response", e); } finally { if (exception != null) { method.releaseConnection(); } } }
From source file:edu.uci.ics.external.connector.asterixdb.ConnectorUtils.java
private static int executeHttpMethod(HttpMethod method) throws Exception { HttpClient client = new HttpClient(); int statusCode; try {// w w w. j a v a 2s . c o m statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { JSONObject result = new JSONObject( new JSONTokener(new InputStreamReader(method.getResponseBodyAsStream()))); if (result.has("error-code")) { String[] errors = { result.getJSONArray("error-code").getString(0), result.getString("summary"), result.getString("stacktrace") }; throw new Exception("HTTP operation failed: " + errors[0] + "\nSTATUS LINE: " + method.getStatusLine() + "\nSUMMARY: " + errors[1] + "\nSTACKTRACE: " + errors[2]); } } return statusCode; } catch (Exception e) { throw e; } finally { method.releaseConnection(); } }
From source file:fi.csc.mobileauth.shibboleth.rest.MobileServiceLoginHandler.java
private static StatusResponse getStatusResponse(String uri) { HttpMethod httpMethod = executeUriCall(uri); if (httpMethod == null) { log.debug("Could not execute call to URL {}", uri); return null; }// w w w. jav a 2s . co m try { InputStream content = httpMethod.getResponseBodyAsStream(); ObjectMapper objectMapper = new ObjectMapper(); StatusResponse response = objectMapper.readValue(content, StatusResponse.class); content.close(); log.debug("Status response eventId={}, errorMessage={}", response.getEventId(), response.getErrorMessage()); return response; } catch (IOException e) { log.error("Could not obtain response from the REST service!", e); return null; } finally { httpMethod.releaseConnection(); } }
From source file:edu.du.penrose.systems.util.HttpClientUtils.java
/** * Get file from URL, directories are created and files overwritten. * /*from www . jav a2 s .co m*/ * * @deprecated use org.apache.commons.io.FileUtils.copyURLToFile(URL, File) * @param requestUrl * @param outputPathAndFileName * * @return int request status code OR -1 if an exception occurred */ static public int getToFile(String requestUrl, String outputPathAndFileName) { int resultStatus = -1; File outputFile = new File(outputPathAndFileName); String outputPath = outputFile.getAbsolutePath().replace(outputFile.getName(), ""); File outputDir = new File(outputPath); if (!outputDir.exists()) { outputDir.mkdir(); } HttpClient client = new HttpClient(); // client.getState().setCredentials( // new AuthScope("localhost", 7080, null ), // new UsernamePasswordCredentials("nation", "nationPW") // ); // client.getParams().setAuthenticationPreemptive(true); HttpMethod method = new GetMethod(requestUrl); // method.setDoAuthentication( true ); // client.getParams().setAuthenticationPreemptive(true); // Execute and print response try { OutputStream os = new FileOutputStream(outputFile); client.executeMethod(method); InputStream is = method.getResponseBodyAsStream(); BufferedInputStream bis = new BufferedInputStream(is); byte[] bytes = new byte[8192]; // reading as chunk of 8192 bytes int count = bis.read(bytes); while (count != -1 && count <= 8192) { os.write(bytes, 0, count); count = bis.read(bytes); } bis.close(); os.close(); resultStatus = method.getStatusCode(); } catch (Exception e) { e.printStackTrace(); } finally { method.releaseConnection(); } return resultStatus; }
From source file:com.gm.machine.util.CommonUtils.java
/** * /*from ww w . j a v a 2 s.c o m*/ * ???? * * @since 2013-1-12 * @author qingang * @param url * ????? * @param remark * * @param path * ?? * @param encoding * ?? * @throws Exception */ public static void createHtmlPage(String url, String remark, String path, String encoding) throws Exception { HttpClient client = new HttpClient(); HttpMethod httpMethod = new PostMethod(url); try { int returnCode = client.executeMethod(httpMethod); if (returnCode == HttpStatus.SC_OK) { BufferedReader reader = new BufferedReader( new InputStreamReader(httpMethod.getResponseBodyAsStream(), "ISO-8859-1")); String tmp = null; StringBuffer htmlRet = new StringBuffer(); while ((tmp = reader.readLine()) != null) { htmlRet.append(tmp + "\n"); } writeHtml(path, Global.HMTLPAGE_CHARSET + new String(htmlRet.toString().getBytes("ISO-8859-1"), encoding), encoding); System.out.println("??=====================??" + remark + "===" + url + "===??:" + path + "===?" + getCurrentDate("yyyy-MM-dd HH:mm") + "======================="); } else if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) { System.err.println("The Post method is not implemented by this URI"); } } catch (Exception e) { System.err.println(e); System.out.println("?=====================??" + remark + "===" + url + "===??:" + path + "===?" + getCurrentDate("yyyy-MM-dd HH:mm") + "======================="); e.printStackTrace(); throw e; } finally { httpMethod.releaseConnection(); } }
From source file:edu.unc.lib.dl.ui.service.XMLRetrievalService.java
public static Document getXMLDocument(String url) throws HttpException, IOException, JDOMException { SAXBuilder builder = new SAXBuilder(); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); method.getParams().setParameter("http.socket.timeout", new Integer(2000)); method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); method.getParams().setParameter("http.useragent", ""); InputStream responseStream = null; Document document = null;//from ww w .j ava2 s . c om try { client.executeMethod(method); responseStream = method.getResponseBodyAsStream(); document = builder.build(responseStream); } finally { if (responseStream != null) responseStream.close(); method.releaseConnection(); } return document; }
From source file:com.xpn.xwiki.plugin.feed.XWikiFeedFetcher.java
/** * @param urlStr//from w w w. jav a 2s. c om * @param method * @return * @throws IOException * @throws HttpException * @throws FetcherException * @throws FeedException */ private static SyndFeed retrieveFeed(String urlStr, HttpMethod method) throws IOException, FetcherException, FeedException { InputStream stream = null; if ((method.getResponseHeader("Content-Encoding") != null) && ("gzip".equalsIgnoreCase(method.getResponseHeader("Content-Encoding").getValue()))) { stream = new GZIPInputStream(method.getResponseBodyAsStream()); } else { stream = method.getResponseBodyAsStream(); } try { XmlReader reader = null; if (method.getResponseHeader("Content-Type") != null) { reader = new XmlReader(stream, method.getResponseHeader("Content-Type").getValue(), true); } else { reader = new XmlReader(stream, true); } return new SyndFeedInput().build(reader); } finally { if (stream != null) { stream.close(); } } }
From source file:apm.common.utils.HttpTookit.java
/** * HTTP GET?HTML/*from ww w . j av a2s .c om*/ * * @param url * URL? * @param queryString * ?,?null * @param charset * * @param pretty * ? * @return ?HTML */ public static String doGet(String url, String queryString, String charset, boolean pretty) { StringBuffer response = new StringBuffer(); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); try { if (StringUtils.isNotBlank(queryString)) // get??http?????%? method.setQueryString(URIUtil.encodeQuery(queryString)); client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { BufferedReader reader = new BufferedReader( new InputStreamReader(method.getResponseBodyAsStream(), charset)); String line; while ((line = reader.readLine()) != null) { if (pretty) { response.append(line).append(System.getProperty("line.separator")); } else { response.append(line); } } reader.close(); } } catch (URIException e) { log.error("HTTP Get?" + queryString + "???", e); } catch (IOException e) { log.error("HTTP Get" + url + "??", e); } finally { method.releaseConnection(); } return response.toString(); }
From source file:it.geosolutions.mariss.wps.gs.DownloadProcess.java
private static boolean downloadVectorDataFromLocalhost(String url, File outDest, HttpConnectionManager manager) throws ProcessException { HttpClient client = new HttpClient(manager); HttpMethod method = new GetMethod(url); OutputStream out = null;//from w w w . jav a2 s . com InputStream in = null; try { client.executeMethod(method); out = new FileOutputStream(outDest); in = method.getResponseBodyAsStream(); IOUtils.copy(in, out); } catch (Exception e) { LOGGER.severe(e.getMessage()); throw new ProcessException("error in vector data download..."); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOGGER.severe(e.getMessage()); } } if (out != null) { try { out.close(); } catch (IOException e) { LOGGER.severe(e.getMessage()); } } } LOGGER.info("Vector Resource downloaded"); return true; }
From source file:apm.common.utils.HttpTookit.java
/** * HTTP POST?HTML// w w w. j a v a 2 s.c o m * * @param url * URL? * @param params * ?,?null * @param charset * * @param pretty * ? * @return ?HTML */ public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) { StringBuffer response = new StringBuffer(); HttpClient client = new HttpClient(); HttpMethod method = new PostMethod(url); // Http Post? if (params != null) { HttpMethodParams p = new HttpMethodParams(); for (Map.Entry<String, String> entry : params.entrySet()) { p.setParameter(entry.getKey(), entry.getValue()); } method.setParams(p); } try { client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { BufferedReader reader = new BufferedReader( new InputStreamReader(method.getResponseBodyAsStream(), charset)); String line; while ((line = reader.readLine()) != null) { if (pretty) { response.append(line).append(System.getProperty("line.separator")); } else { response.append(line); } } reader.close(); } } catch (IOException e) { log.error("HTTP Post" + url + "??", e); } finally { method.releaseConnection(); } return response.toString(); }