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.zimbra.cs.dav.client.WebDavClient.java

public Collection<DavObject> sendMultiResponseRequest(DavRequest req) throws IOException, DavException {
    ArrayList<DavObject> ret = new ArrayList<DavObject>();

    HttpMethod m = null;
    try {//from  w  ww. j  a  v a2  s . com
        m = executeFollowRedirect(req);
        int status = m.getStatusCode();
        if (status >= 400) {
            throw new DavException("DAV server returned an error: " + status, status);
        }

        Document doc = W3cDomUtil.parseXMLToDom4jDocUsingSecureProcessing(m.getResponseBodyAsStream());
        Element top = doc.getRootElement();
        for (Object obj : top.elements(DavElements.E_RESPONSE)) {
            if (obj instanceof Element) {
                ret.add(new DavObject((Element) obj));
            }
        }
    } catch (XmlParseException e) {
        throw new DavException("can't parse response", e);
    } finally {
        if (m != null) {
            m.releaseConnection();
        }
    }
    return ret;
}

From source file:com.cloud.test.stress.StressTestDirectAttach.java

private static int executeStop(String server, String developerServer, String username)
        throws HttpException, IOException {
    // test steps:
    // - get userId for the given username
    // - list virtual machines for the user
    // - stop all virtual machines
    // - get ip addresses for the user
    // - release ip addresses

    // -----------------------------
    // GET USER// w  w  w .j a v  a2  s . c o m
    // -----------------------------
    String userId = _userId.get().toString();
    String encodedUserId = URLEncoder.encode(userId, "UTF-8");

    String url = server + "?command=listUsers&id=" + encodedUserId;
    s_logger.info("Stopping resources for user: " + username);
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    int responseCode = client.executeMethod(method);
    s_logger.info("get user response code: " + responseCode);
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> userIdValues = getSingleValueFromXML(is, new String[] { "id" });
        String userIdStr = userIdValues.get("id");
        if (userIdStr != null) {
            userId = userIdStr;
            if (userId == null) {
                s_logger.error("get user failed to retrieve a valid user id, aborting depolyment test"
                        + ". Following URL was sent: " + url);
                return -1;
            }
        }
    } else {
        s_logger.error("get user failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }

    {
        // ----------------------------------
        // LIST VIRTUAL MACHINES
        // ----------------------------------
        String encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8");
        String requestToSign = "apikey=" + encodedApiKey + "&command=listVirtualMachines";
        requestToSign = requestToSign.toLowerCase();
        String signature = signRequest(requestToSign, _secretKey.get());
        String encodedSignature = URLEncoder.encode(signature, "UTF-8");

        url = developerServer + "?command=listVirtualMachines&apikey=" + encodedApiKey + "&signature="
                + encodedSignature;

        s_logger.info("Listing all virtual machines for the user with url " + url);
        String[] vmIds = null;
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        s_logger.info("list virtual machines response code: " + responseCode);
        if (responseCode == 200) {
            InputStream is = method.getResponseBodyAsStream();
            Map<String, List<String>> vmIdValues = getMultipleValuesFromXML(is, new String[] { "id" });
            if (vmIdValues.containsKey("id")) {
                List<String> vmIdList = vmIdValues.get("id");
                if (vmIdList != null) {
                    vmIds = new String[vmIdList.size()];
                    vmIdList.toArray(vmIds);
                    String vmIdLogStr = "";
                    if ((vmIds != null) && (vmIds.length > 0)) {
                        vmIdLogStr = vmIds[0];
                        for (int i = 1; i < vmIds.length; i++) {
                            vmIdLogStr = vmIdLogStr + "," + vmIds[i];
                        }
                    }
                    s_logger.info("got virtual machine ids: " + vmIdLogStr);
                }
            }

        } else {
            s_logger.error("list virtual machines test failed with error code: " + responseCode
                    + ". Following URL was sent: " + url);
            return responseCode;
        }

        // ----------------------------------
        // STOP/DESTROY VIRTUAL MACHINES
        // ----------------------------------
        if (vmIds != null) {
            for (String vmId : vmIds) {
                requestToSign = "apikey=" + encodedApiKey + "&command=stopVirtualMachine&id=" + vmId;
                requestToSign = requestToSign.toLowerCase();
                signature = signRequest(requestToSign, _secretKey.get());
                encodedSignature = URLEncoder.encode(signature, "UTF-8");

                url = developerServer + "?command=stopVirtualMachine&id=" + vmId + "&apikey=" + encodedApiKey
                        + "&signature=" + encodedSignature;
                client = new HttpClient();
                method = new GetMethod(url);
                responseCode = client.executeMethod(method);
                s_logger.info("StopVirtualMachine" + " [" + vmId + "] response code: " + responseCode);
                if (responseCode == 200) {
                    InputStream input = method.getResponseBodyAsStream();
                    Element el = queryAsyncJobResult(server, input);
                    Map<String, String> success = getSingleValueFromXML(el, new String[] { "success" });
                    s_logger.info("StopVirtualMachine..success? " + success.get("success"));
                } else {
                    s_logger.error("Stop virtual machine test failed with error code: " + responseCode
                            + ". Following URL was sent: " + url);
                    return responseCode;
                }
            }
        }

        //         {
        //            url = server + "?command=deleteUser&id=" + userId;
        //            client = new HttpClient();
        //            method = new GetMethod(url);
        //            responseCode = client.executeMethod(method);
        //            s_logger.info("delete user response code: " + responseCode);
        //            if (responseCode == 200) {
        //               InputStream input = method.getResponseBodyAsStream();
        //               Element el = queryAsyncJobResult(server, input);
        //               s_logger
        //                     .info("Deleted user successfully");
        //            } else  {
        //               s_logger.error("delete user failed with error code: " + responseCode + ". Following URL was sent: " + url);
        //               return responseCode;
        //            } 
        //         }

    }

    _linuxIP.set("");
    _linuxVmId.set("");
    _linuxPassword.set("");
    _windowsIP.set("");
    _secretKey.set("");
    _apiKey.set("");
    _userId.set(Long.parseLong("0"));
    _account.set("");
    _domainRouterId.set("");
    return responseCode;
}

From source file:com.panet.imeta.trans.steps.http.HTTP.java

private Object[] callHttpService(RowMetaInterface rowMeta, Object[] rowData) throws KettleException {
    String url = determineUrl(rowMeta, rowData);
    try {//from   w ww  .j a va2s. co m
        if (log.isDetailed())
            logDetailed(Messages.getString("HTTP.Log.Connecting", url));

        // Prepare HTTP get
        // 
        HttpClient httpclient = new HttpClient();
        HttpMethod method = new GetMethod(environmentSubstitute(url));

        // Execute request
        // 
        try {
            int result = httpclient.executeMethod(method);

            // The status code
            if (log.isDebug())
                log.logDebug(toString(), Messages.getString("HTTP.Log.ResponseStatusCode", "" + result));

            // the response
            InputStream inputStream = method.getResponseBodyAsStream();
            StringBuffer bodyBuffer = new StringBuffer();
            int c;
            while ((c = inputStream.read()) != -1)
                bodyBuffer.append((char) c);
            inputStream.close();

            String body = bodyBuffer.toString();
            if (log.isDebug())
                log.logDebug(toString(), "Response body: " + body);

            return RowDataUtil.addValueData(rowData, rowMeta.size(), body);
        } finally {
            // Release current connection to the connection pool once you are done
            method.releaseConnection();
        }
    } catch (Exception e) {
        throw new KettleException(Messages.getString("HTTP.Log.UnableGetResult", url), e);
    }
}

From source file:net.sourceforge.eclipsetrader.opentick.Feed.java

public void snapshot() {
    SimpleDateFormat usDateTimeParser = new SimpleDateFormat("MM/dd/yyyy h:mma");
    SimpleDateFormat usDateParser = new SimpleDateFormat("MM/dd/yyyy");
    SimpleDateFormat usTimeParser = new SimpleDateFormat("h:mma");
    NumberFormat numberFormat = NumberFormat.getInstance(Locale.US);

    // Builds the url for quotes download
    String host = "quote.yahoo.com";
    StringBuffer url = new StringBuffer("http://" + host + "/download/javasoft.beans?symbols=");
    for (Iterator iter = subscribedSecurities.iterator(); iter.hasNext();) {
        Security security = (Security) iter.next();
        url = url.append(security.getCode() + "+");
    }// www .j a  va 2 s.c om
    if (url.charAt(url.length() - 1) == '+')
        url.deleteCharAt(url.length() - 1);
    url.append("&format=sl1d1t1c1ohgvbap");

    // Read the last prices
    String line = "";
    try {
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        BundleContext context = OpenTickPlugin.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()));
        while ((line = in.readLine()) != null) {
            String[] item = line.split(",");
            if (line.indexOf(";") != -1)
                item = line.split(";");

            Double open = null, high = null, low = null, close = null;
            Quote quote = new Quote();

            // 2 = Date
            // 3 = Time
            try {
                GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone("EST"), Locale.US);
                usDateTimeParser.setTimeZone(c.getTimeZone());
                usDateParser.setTimeZone(c.getTimeZone());
                usTimeParser.setTimeZone(c.getTimeZone());

                String date = stripQuotes(item[2]);
                if (date.indexOf("N/A") != -1)
                    date = usDateParser.format(Calendar.getInstance().getTime());
                String time = stripQuotes(item[3]);
                if (time.indexOf("N/A") != -1)
                    time = usTimeParser.format(Calendar.getInstance().getTime());
                c.setTime(usDateTimeParser.parse(date + " " + time));
                c.setTimeZone(TimeZone.getDefault());
                quote.setDate(c.getTime());
            } catch (Exception e) {
                System.out.println(e.getMessage() + ": " + line);
            }
            // 1 = Last price or N/A
            if (item[1].equalsIgnoreCase("N/A") == false)
                quote.setLast(numberFormat.parse(item[1]).doubleValue());
            // 4 = Change
            // 5 = Open
            if (item[5].equalsIgnoreCase("N/A") == false)
                open = new Double(numberFormat.parse(item[5]).doubleValue());
            // 6 = Maximum
            if (item[6].equalsIgnoreCase("N/A") == false)
                high = new Double(numberFormat.parse(item[6]).doubleValue());
            // 7 = Minimum
            if (item[7].equalsIgnoreCase("N/A") == false)
                low = new Double(numberFormat.parse(item[7]).doubleValue());
            // 8 = Volume
            if (item[8].equalsIgnoreCase("N/A") == false)
                quote.setVolume(numberFormat.parse(item[8]).intValue());
            // 9 = Bid Price
            if (item[9].equalsIgnoreCase("N/A") == false)
                quote.setBid(numberFormat.parse(item[9]).doubleValue());
            // 10 = Ask Price
            if (item[10].equalsIgnoreCase("N/A") == false)
                quote.setAsk(numberFormat.parse(item[10]).doubleValue());
            // 11 = Close Price
            if (item[11].equalsIgnoreCase("N/A") == false)
                close = new Double(numberFormat.parse(item[11]).doubleValue());

            // 0 = Code
            String symbol = stripQuotes(item[0]);
            for (Iterator iter = subscribedSecurities.iterator(); iter.hasNext();) {
                Security security = (Security) iter.next();
                if (symbol.equalsIgnoreCase(security.getCode()))
                    security.setQuote(quote, open, high, low, close);
            }
        }
        in.close();
    } catch (Exception e) {
        System.out.println(e.getMessage() + ": " + line);
        e.printStackTrace();
    }
}

From source file:com.sun.syndication.fetcher.impl.HttpClientFeedFetcher.java

/**
* @param client/*from  w  w w.  j  a v  a2s  .  c o m*/
* @param urlStr
* @param method
* @return
* @throws IOException
* @throws HttpException
* @throws FetcherException
* @throws FeedException
*/
private SyndFeed retrieveFeed(String urlStr, HttpMethod method)
        throws IOException, HttpException, 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);
        }
        SyndFeedInput syndFeedInput = new SyndFeedInput();
        syndFeedInput.setPreserveWireFeed(isPreserveWireFeed());

        return syndFeedInput.build(reader);
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}

From source file:jhc.redsniff.webdriver.download.FileDownloader.java

private void doDownloadUrlToFile(URL downloadURL, File downloadFile) throws Exception {
    HttpClient client = createHttpClient(downloadURL);
    HttpMethod getRequest = new GetMethod(downloadURL.toString());
    try {//from w ww .  ja v  a  2s .  c  o m
        int status = -1;
        for (int attempts = 0; attempts < MAX_ATTEMPTS && status != HTTP_SUCCESS_CODE; attempts++)
            status = client.executeMethod(getRequest);
        if (status != HTTP_SUCCESS_CODE)
            throw new Exception("Got " + status + " status trying to download file " + downloadURL.toString()
                    + " to " + downloadFile.toString());
        BufferedInputStream in = new BufferedInputStream(getRequest.getResponseBodyAsStream());
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(downloadFile));
        int offset = 0;
        int len = 4096;
        int bytes = 0;
        byte[] block = new byte[len];
        while ((bytes = in.read(block, offset, len)) > -1) {
            out.write(block, 0, bytes);
        }
        out.close();
        in.close();
    } catch (Exception e) {
        throw e;
    } finally {
        getRequest.releaseConnection();
    }
}

From source file:com.yahoo.flowetl.services.HttpService.java

/**
 * Calls the given http params and returns a result object.
 * //from   ww  w.j a  va2 s .  c  o m
 * @param params
 * 
 * @return the http result
 */
public HttpResult call(HttpParams params) {
    Pair<HttpClient, HttpMethod> clientMet = generator.generate(params);
    HttpClient client = clientMet.getFirst();
    HttpMethod toCall = clientMet.getSecond();
    HttpResult out = new HttpResult();
    out.statusCode = -1;
    out.sourceParams = params;
    InputStream is = null;
    try {
        if (logger.isEnabled(Level.INFO)) {
            logger.log(Level.INFO, "Running http method " + toCall + " with params " + params);
        }
        caller.execute(client, toCall, params.retries);
        is = toCall.getResponseBodyAsStream();
        String responseBody = IOUtils.toString(is);
        int st = toCall.getStatusCode();
        Header[] hv = toCall.getResponseHeaders();
        // copy over
        out.statusCode = st;
        out.responseBody = responseBody;
        Map<String, String> headersIn = new TreeMap<String, String>();
        if (hv != null) {
            for (Header h : hv) {
                headersIn.put(h.getName(), h.getValue());
            }
        }
        out.headers = headersIn;
    } catch (HttpException e) {
        if (logger.isEnabled(Level.WARN)) {
            logger.log(Level.WARN, e, "Failed calling " + toCall);
        }
    } catch (IOException e) {
        if (logger.isEnabled(Level.WARN)) {
            logger.log(Level.WARN, e, "Failed calling " + toCall);
        }
    } finally {
        IOUtils.closeQuietly(is);
        toCall.releaseConnection();
    }
    return out;
}

From source file:com.discogs.api.webservice.impl.HttpClientWebService.java

@Override
public Resp doGet(String url) throws WebServiceException {
    HttpMethod method = new GZipCapableGetMethod(url);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    method.setDoAuthentication(true);//from www  .j  a v a  2  s  .c o  m

    try {
        // execute the method
        int statusCode = this.httpClient.executeMethod(method);

        if (logger.isDebugEnabled()) {
            logger.debug(method.getResponseBodyAsString());
        }

        switch (statusCode) {
        case HttpStatus.SC_OK:
            return createResp(method.getResponseBodyAsStream());

        case HttpStatus.SC_NOT_FOUND:
            throw new ResourceNotFoundException("Resource not found.", method.getResponseBodyAsString());

        case HttpStatus.SC_BAD_REQUEST:
            throw new RequestException(method.getResponseBodyAsString());

        case HttpStatus.SC_FORBIDDEN:
            throw new AuthorizationException(method.getResponseBodyAsString());

        case HttpStatus.SC_UNAUTHORIZED:
            throw new AuthorizationException(method.getResponseBodyAsString());

        default:
            String em = "web service returned unknown status '" + statusCode + "', response was: "
                    + method.getResponseBodyAsString();
            logger.error(em);
            throw new WebServiceException(em);
        }
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: " + e.getMessage());
        throw new WebServiceException(e.getMessage(), e);
    } catch (IOException e) {
        logger.error("Fatal transport error: " + e.getMessage());
        throw new WebServiceException(e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.cloud.test.stress.StressTestDirectAttach.java

private static int executeCleanup(String server, String developerServer, String username)
        throws HttpException, IOException {
    // test steps:
    // - get user
    // - delete user

    // -----------------------------
    // GET USER/*w w  w. j  av a  2 s.  c om*/
    // -----------------------------
    String userId = _userId.get().toString();
    String encodedUserId = URLEncoder.encode(userId, "UTF-8");
    String url = server + "?command=listUsers&id=" + encodedUserId;
    s_logger.info("Cleaning up resources for user: " + userId + " with url " + url);
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    int responseCode = client.executeMethod(method);
    s_logger.info("get user response code: " + responseCode);
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> userInfo = getSingleValueFromXML(is, new String[] { "username", "id", "account" });
        if (!username.equals(userInfo.get("username"))) {
            s_logger.error("get user failed to retrieve requested user, aborting cleanup test"
                    + ". Following URL was sent: " + url);
            return -1;
        }

    } else {
        s_logger.error("get user failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }

    // -----------------------------
    // UPDATE USER
    // -----------------------------
    {
        url = server + "?command=updateUser&id=" + userId + "&firstname=delete&lastname=me";
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        s_logger.info("update user response code: " + responseCode);
        if (responseCode == 200) {
            InputStream is = method.getResponseBodyAsStream();
            Map<String, String> success = getSingleValueFromXML(is, new String[] { "success" });
            s_logger.info("update user..success? " + success.get("success"));
        } else {
            s_logger.error(
                    "update user failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }

    // -----------------------------
    // Execute reboot/stop/start commands for the VMs before deleting the account - made to exercise xen
    // -----------------------------

    //Reboot centos VM
    String encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8");
    String requestToSign = "apikey=" + encodedApiKey + "&command=rebootVirtualMachine&id=" + _linuxVmId.get();
    requestToSign = requestToSign.toLowerCase();
    String signature = signRequest(requestToSign, _secretKey.get());
    String encodedSignature = URLEncoder.encode(signature, "UTF-8");

    url = developerServer + "?command=rebootVirtualMachine&id=" + _linuxVmId.get() + "&apikey=" + encodedApiKey
            + "&signature=" + encodedSignature;
    client = new HttpClient();
    method = new GetMethod(url);
    responseCode = client.executeMethod(method);
    s_logger.info("Reboot VM response code: " + responseCode);
    if (responseCode == 200) {
        InputStream input = method.getResponseBodyAsStream();
        Element el = queryAsyncJobResult(server, input);
        Map<String, String> success = getSingleValueFromXML(el, new String[] { "success" });
        s_logger.info("VM was rebooted with the status: " + success.get("success"));
    } else {
        s_logger.error(" VM test failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }

    //Stop centos VM
    requestToSign = "apikey=" + encodedApiKey + "&command=stopVirtualMachine&id=" + _linuxVmId.get();
    requestToSign = requestToSign.toLowerCase();
    signature = signRequest(requestToSign, _secretKey.get());
    encodedSignature = URLEncoder.encode(signature, "UTF-8");

    url = developerServer + "?command=stopVirtualMachine&id=" + _linuxVmId.get() + "&apikey=" + encodedApiKey
            + "&signature=" + encodedSignature;
    client = new HttpClient();
    method = new GetMethod(url);
    responseCode = client.executeMethod(method);
    s_logger.info("Stop VM response code: " + responseCode);
    if (responseCode == 200) {
        InputStream input = method.getResponseBodyAsStream();
        Element el = queryAsyncJobResult(server, input);
        Map<String, String> success = getSingleValueFromXML(el, new String[] { "success" });
        s_logger.info("VM was stopped with the status: " + success.get("success"));
    } else {
        s_logger.error(
                "Stop VM test failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }

    //Start centos VM
    requestToSign = "apikey=" + encodedApiKey + "&command=startVirtualMachine&id=" + _linuxVmId.get();
    requestToSign = requestToSign.toLowerCase();
    signature = signRequest(requestToSign, _secretKey.get());
    encodedSignature = URLEncoder.encode(signature, "UTF-8");

    url = developerServer + "?command=startVirtualMachine&id=" + _linuxVmId.get() + "&apikey=" + encodedApiKey
            + "&signature=" + encodedSignature;
    client = new HttpClient();
    method = new GetMethod(url);
    responseCode = client.executeMethod(method);
    s_logger.info("Start VM response code: " + responseCode);

    if (responseCode == 200) {
        InputStream input = method.getResponseBodyAsStream();
        Element el = queryAsyncJobResult(server, input);
        Map<String, String> success = getSingleValueFromXML(el, new String[] { "id" });

        if (success.get("id") == null) {
            s_logger.info("Start linux vm response code: 401");
            return 401;
        } else {
            s_logger.info("Start vm response code: " + responseCode);
        }

        s_logger.info("VM was started with the status: " + success.get("success"));
    } else {
        s_logger.error(
                "Start VM test failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }

    ////      // -----------------------------
    ////      // DISABLE USER
    ////      // -----------------------------
    //      {
    //         url = server + "?command=disableUser&id=" + userId;
    //         client = new HttpClient();
    //         method = new GetMethod(url);
    //         responseCode = client.executeMethod(method);
    //         s_logger.info("disable user response code: " + responseCode);
    //         if (responseCode == 200) {
    //            InputStream input = method.getResponseBodyAsStream();
    //            Element el = queryAsyncJobResult(server, input);
    //            s_logger
    //                  .info("Disabled user successfully");
    //         } else  {
    //            s_logger.error("disable user failed with error code: " + responseCode + ". Following URL was sent: " + url);
    //            return responseCode;
    //         } 
    //      }

    // -----------------------------
    // DELETE USER
    // -----------------------------
    {
        url = server + "?command=deleteUser&id=" + userId;
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        s_logger.info("delete user response code: " + responseCode);
        if (responseCode == 200) {
            InputStream input = method.getResponseBodyAsStream();
            Element el = queryAsyncJobResult(server, input);
            s_logger.info("Deleted user successfully");
        } else {
            s_logger.error(
                    "delete user failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }
    return responseCode;
}

From source file:net.sourceforge.eclipsetrader.core.CurrencyConverter.java

private Double downloadQuote(String symbol) {
    Double result = null;/*from  www  .j  ava  2  s  .  c om*/

    String host = "quote.yahoo.com"; //$NON-NLS-1$
    StringBuffer url = new StringBuffer("http://" + host + "/download/javasoft.beans?symbols="); //$NON-NLS-1$ //$NON-NLS-2$
    url = url.append(symbol + "=X"); //$NON-NLS-1$
    url.append("&format=sl1d1t1c1ohgvbap"); //$NON-NLS-1$

    String line = ""; //$NON-NLS-1$
    try {
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        BundleContext context = CorePlugin.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()));
        while ((line = in.readLine()) != null) {
            String[] item = line.split(","); //$NON-NLS-1$
            if (line.indexOf(";") != -1) //$NON-NLS-1$
                item = line.split(";"); //$NON-NLS-1$

            // 1 = Last price or N/A
            if (item[1].equalsIgnoreCase(Messages.CurrencyConverter_NA) == false)
                result = new Double(numberFormat.parse(item[1]).doubleValue());
            // 2 = Date
            // 3 = Time
            // 4 = Change
            // 5 = Open
            // 6 = Maximum
            // 7 = Minimum
            // 8 = Volume
            // 9 = Bid Price
            // 10 = Ask Price
            // 11 = Close Price

            // 0 = Code
        }
        in.close();
    } catch (Exception e) {
        logger.error(e, e);
    }

    return result;
}