Example usage for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream

List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream.

Prototype

public abstract InputStream getResponseBodyAsStream() throws IOException;

Source Link

Usage

From source file:com.tasktop.c2c.server.web.proxy.HttpProxy.java

void copyProxyReponse(HttpMethod proxyResponse, HttpServletResponse response) throws IOException {
    copyProxyHeaders(proxyResponse.getResponseHeaders(), response);
    response.setContentLength(getResponseContentLength(proxyResponse));
    copy(proxyResponse.getResponseBodyAsStream(), response.getOutputStream());
    if (proxyResponse.getStatusLine() != null) {
        int statCode = proxyResponse.getStatusCode();
        response.setStatus(statCode);//  w  ww  .ja va 2s.  co m
    }
}

From source file:com.twinsoft.convertigo.engine.PacManager.java

private String downloadPacContent(String url) throws IOException {
    if (url == null) {
        Engine.logProxyManager.debug("(PacManager) Invalid PAC script URL: null");
        throw new IOException("Invalid PAC script URL: null");
    }//ww w.  ja  va  2 s  .c om

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);

    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
        throw new IOException("(PacManager) Method failed: " + method.getStatusLine());
    }

    return IOUtils.toString(method.getResponseBodyAsStream(), "UTF-8");
}

From source file:at.ac.tuwien.auto.sewoa.http.HttpRetrieverImpl.java

private byte[] send(HttpClient httpClient, HttpMethod method) {
    try {//w w  w. j  a  v a 2 s  . c  o m
        int httpResult = httpClient.executeMethod(method);
        if (httpResult != HttpURLConnection.HTTP_OK) {
            LOGGER.warn("cannot post data to url {} -> result: {}.", method.getURI().toString(), httpResult);
            ByteStreams.toByteArray(method.getResponseBodyAsStream());
            throw new IllegalStateException("error code");
        } else {
            return ByteStreams.toByteArray(method.getResponseBodyAsStream());
        }
    } catch (Exception e) {
        LOGGER.warn("cannot post http data to url {} due to {}.", method.toString(), e.getMessage());
        throw new IllegalStateException("could not post data");
    }
}

From source file:com.knowledgebooks.info_spiders.DBpediaLookupClient.java

public DBpediaLookupClient(String query) throws Exception {
    this.query = query;
    //System.out.println("\n query: " + query);
    HttpClient client = new HttpClient();

    String query2 = query.replaceAll(" ", "+"); // URLEncoder.encode(query, "utf-8");
    //System.out.println("\n query2: " + query2);
    HttpMethod method = new GetMethod(
            "http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryString=" + query2);
    try {/*from  ww  w. j  av a2 s .c  o m*/
        System.out.println("\n method: " + method.getURI());
        client.executeMethod(method);
        System.out.println(method);
        InputStream ins = method.getResponseBodyAsStream();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser sax = factory.newSAXParser();
        sax.parse(ins, this);
    } catch (HttpException he) {
        System.err.println("Http error connecting to lookup.dbpedia.org");
    } catch (IOException ioe) {
        System.err.println("Unable to connect to lookup.dbpedia.org");
    }
    method.releaseConnection();
}

From source file:net.sourceforge.eclipsetrader.borsaitalia.HistoryFeed.java

public void updateHistory(Security security, int interval) {
    History history = null;//from ww  w . j  ava  2 s  .  c om
    Calendar from = Calendar.getInstance();
    from.set(Calendar.MILLISECOND, 0);

    if (interval < IHistoryFeed.INTERVAL_DAILY) {
        history = security.getIntradayHistory();
        from.set(Calendar.HOUR_OF_DAY, 0);
        from.set(Calendar.MINUTE, 0);
        from.set(Calendar.SECOND, 0);
        log.info("Updating intraday data for " + security.getCode() + " - " + security.getDescription()); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        history = security.getHistory();
        if (history.size() == 0)
            from.add(Calendar.YEAR, -CorePlugin.getDefault().getPreferenceStore()
                    .getInt(CorePlugin.PREFS_HISTORICAL_PRICE_RANGE));
        else {
            Bar cd = history.getLast();
            from.setTime(cd.getDate());
            from.add(Calendar.DATE, 1);
        }
        log.info("Updating historical data for " + security.getCode() + " - " + security.getDescription()); //$NON-NLS-1$ //$NON-NLS-2$
    }

    String symbol = null;
    if (security.getHistoryFeed() != null)
        symbol = security.getHistoryFeed().getSymbol();
    if (symbol == null || symbol.length() == 0)
        symbol = security.getCode();

    String code = security.getCode();
    if (code.indexOf('.') != -1)
        code = code.substring(0, code.indexOf('.'));

    try {
        String host = "194.185.192.223"; // "grafici.borsaitalia.it";
        StringBuffer url = new StringBuffer(
                "http://" + host + "/scripts/cligipsw.dll?app=tic_d&action=dwnld4push&cod=" + code + "&codneb=" //$NON-NLS-1$//$NON-NLS-2$
                        + symbol + "&req_type=GRAF_DS&ascii=1&form_id=");
        if (interval < IHistoryFeed.INTERVAL_DAILY)
            url.append("&period=1MIN"); //$NON-NLS-1$
        else {
            url.append("&period=1DAY"); //$NON-NLS-1$
            url.append("&From=" + df.format(from.getTime())); //$NON-NLS-1$
        }
        log.debug(url);

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        BundleContext context = BorsaitaliaPlugin.getDefault().getBundle().getBundleContext();
        ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
        if (reference != null) {
            IProxyService proxy = (IProxyService) context.getService(reference);
            IProxyData data = proxy.getProxyDataForHost(host, IProxyData.HTTP_PROXY_TYPE);
            if (data != null) {
                if (data.getHost() != null)
                    client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                if (data.isRequiresAuthentication())
                    client.getState().setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
            }
        }

        HttpMethod method = new GetMethod(url.toString());
        method.setFollowRedirects(true);
        client.executeMethod(method);

        BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));

        // The first line is the header, ignoring
        String inputLine = in.readLine();
        log.trace(inputLine);

        while ((inputLine = in.readLine()) != null) {
            log.trace(inputLine);
            if (inputLine.startsWith("@") == true || inputLine.length() == 0) //$NON-NLS-1$
                continue;
            String[] item = inputLine.split("\\|"); //$NON-NLS-1$

            Bar bar = new Bar();
            bar.setDate(df.parse(item[0]));
            bar.setOpen(Double.parseDouble(item[1]));
            bar.setHigh(Double.parseDouble(item[2]));
            bar.setLow(Double.parseDouble(item[3]));
            bar.setClose(Double.parseDouble(item[4]));
            bar.setVolume((long) Double.parseDouble(item[5]));

            // Remove the old bar, if exists
            int index = history.indexOf(bar.getDate());
            if (index != -1)
                history.remove(index);

            history.add(bar);
        }

        in.close();

    } catch (Exception e) {
        CorePlugin.logException(e);
    }

    CorePlugin.getRepository().save(history);
}

From source file:com.sina.stock.SinaStockClient.java

private Bitmap getBitmapFromUrl(String url) throws HttpException, IOException {

    HttpMethod method = new GetMethod(url);
    int statusCode = mHttpClient.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        method.releaseConnection();/*from  www  .  j  a  v  a2  s.c  om*/
        return null;
    }

    InputStream in = method.getResponseBodyAsStream();
    BufferedInputStream bis = new BufferedInputStream(in);

    Bitmap bm = BitmapFactory.decodeStream(bis);

    bis.close();
    method.releaseConnection();

    return bm;
}

From source file:com.clarkparsia.sbol.editor.sparql.StardogEndpoint.java

@Override
public boolean executeAskQuery(String query) throws QueryEvaluationException {
    try {// ww  w .j  a  va 2 s  . c  o m
        Boolean result = null;
        HttpMethod response = executeQuery(query);
        try {
            InputStream in = response.getResponseBodyAsStream();
            result = booleanParser.parse(in);
            return result.booleanValue();
        } catch (HttpException e) {
            throw new QueryEvaluationException(e);
        } catch (QueryResultParseException e) {
            throw new QueryEvaluationException(e);
        } finally {
            if (result == null) {
                response.abort();
            }
        }
    } catch (IOException e) {
        throw new QueryEvaluationException(e);
    }
}

From source file:colt.nicity.performance.latent.http.ApacheHttpClient.java

HttpResponse execute(HttpMethod method) throws IOException {

    applyHeadersCommonToAllRequests(method);

    byte[] responseBody;
    StatusLine statusLine;/* w ww  .  j  ava2s  .  co  m*/
    try {
        client.executeMethod(method);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        InputStream responseBodyAsStream = method.getResponseBodyAsStream();
        if (responseBodyAsStream != null) {
            copyLarge(responseBodyAsStream, outputStream, new byte[1024 * 4]);
        }

        responseBody = outputStream.toByteArray();
        statusLine = method.getStatusLine();

        // Catch exception and log error here? or silently fail?
    } finally {
        method.releaseConnection();
    }

    return new HttpResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase(), responseBody);
}

From source file:com.sina.stock.SinaStockClient.java

/**
 * ???//  ww w . j a  va 2 s .c  o m
 * 
 * @param stockCodes 
 *       ??"sh+?", ?"sz+?"
 * 
 * @return ?List<SinaStockInfo>null 
 *       
 * @throws IOException 
 * @throws HttpException 
 * @throws ParseStockInfoException 
 */
public List<SinaStockInfo> getStockInfo(String[] stockCodes)
        throws HttpException, IOException, ParseStockInfoException {
    String url = STOCK_URL + generateStockCodeRequest(stockCodes);

    HttpMethod method = new GetMethod(url);
    int statusCode = mHttpClient.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        method.releaseConnection();
        return null;
    }

    InputStream is = method.getResponseBodyAsStream();
    InputStreamReader reader = new InputStreamReader(new BufferedInputStream(is), Charset.forName("gbk"));
    BufferedReader bReader = new BufferedReader(reader);

    List<SinaStockInfo> list = parseSinaStockInfosFromReader(bReader);
    bReader.close();
    method.releaseConnection();

    return list;
}

From source file:io.hops.hopsworks.api.admin.YarnUIProxyServlet.java

protected void copyResponseEntity(HttpMethod method, HttpServletResponse servletResponse) throws IOException {
    InputStream entity = method.getResponseBodyAsStream();
    if (entity != null) {
        OutputStream servletOutputStream = servletResponse.getOutputStream();
        if (servletResponse.getHeader("Content-Type") == null
                || servletResponse.getHeader("Content-Type").contains("html")) {
            String inputLine;//from   www .j  av  a2s  . co  m
            BufferedReader br = new BufferedReader(new InputStreamReader(entity));

            try {
                int contentSize = 0;
                String source = "http://" + method.getURI().getHost() + ":" + method.getURI().getPort();
                while ((inputLine = br.readLine()) != null) {
                    String outputLine = hopify(inputLine, source) + "\n";
                    byte[] output = outputLine.getBytes(Charset.forName("UTF-8"));
                    servletOutputStream.write(output);
                    contentSize += output.length;
                }
                br.close();
                servletResponse.setHeader("Content-Length", Integer.toString(contentSize));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            org.apache.hadoop.io.IOUtils.copyBytes(entity, servletOutputStream, 4096, doLog);
        }
    }
}