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.amazonaws.sqs.util.HttpResponse.java

public static HttpResponse parseMethod(HttpMethod method) throws IOException {
    int httpStatusCode = method.getStatusCode();
    InputStream in = method.getResponseBodyAsStream();

    int numRead = -1;
    byte[] buf = new byte[4 * 1024];

    String responseBody = new String("");

    while ((numRead = in.read(buf)) != -1) {
        String str = new String(buf, 0, numRead);
        responseBody = responseBody + str;
    }//w w  w .  j  a  va 2 s. c  o m
    method.releaseConnection();
    return new HttpResponse(responseBody, httpStatusCode);
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.file.RemoteFileReader.java

public static InputStream getInputStream(URL url, String user, String password)
        throws HttpException, IOException {
    InputStream inputStream;//  w  ww  .ja  va  2s .c o m
    if (StringUtils.isEmpty(user) && StringUtils.isEmpty(password)) {
        inputStream = url.openConnection().getInputStream();
    } else {
        HttpMethod getMethod = httpGet(url.toExternalForm(), user, password);
        inputStream = getMethod.getResponseBodyAsStream();
    }
    return inputStream;
}

From source file:com.criticalsoftware.mobics.presentation.util.GeolocationUtil.java

private static byte[] readResponse(HttpMethod method) throws IOException {
    InputStream is = method.getResponseBodyAsStream();
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int nRead;//from  w  ww .  j  ava  2s. co  m
    byte[] data = new byte[16384];
    while ((nRead = is.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }

    buffer.flush();
    byte[] responseBody = buffer.toByteArray();
    return responseBody;
}

From source file:com.intellij.diagnostic.DevelopersLoader.java

public static Collection<Developer> fetchDevelopers(ProgressIndicator indicator) throws IOException {
    List<Developer> developers = new LinkedList<Developer>();
    developers.add(Developer.NULL);/* w w w  .  j  a  v a2s .  com*/

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT);
    HttpMethod method = new GetMethod(DEVELOPERS_LIST_URL);

    try {
        client.executeMethod(method);

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(method.getResponseBodyAsStream(), DATA_CHARSET));

        try {
            while (true) {
                String line = reader.readLine();
                if (line == null)
                    break;
                int i = line.indexOf('\t');
                if (i == -1)
                    throw new IOException("Protocol error");
                int id = Integer.parseInt(line.substring(0, i));
                String name = line.substring(i + 1);
                developers.add(new Developer(id, name));
                indicator.checkCanceled();
            }
            return developers;
        } finally {
            reader.close();
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:com.sun.jersey.client.apache.ApacheHttpClientHandler.java

private static InputStream getInputStream(HttpMethod method) throws IOException {
    InputStream i = method.getResponseBodyAsStream();

    if (i == null) {
        return new ByteArrayInputStream(new byte[0]);
    } else if (i.markSupported()) {
        return i;
    } else {//  w  w  w  .j  a va  2s .c om
        return new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE);
    }
}

From source file:edu.umd.cs.buildServer.util.IO.java

/**
 * Read file from HTTP response body into a file.
 *
 * @param file//from  w ww  . j  av  a2  s .c o m
 *            a File in the filesystem where the file should be stored
 * @param method
 *            the HttpMethod representing the request and response
 * @throws IOException
 *             if the complete file couldn't be downloaded
 */
public static void download(File file, HttpMethod method) throws IOException {
    InputStream in = null;
    OutputStream out = null;

    try {
        in = new BufferedInputStream(method.getResponseBodyAsStream());
        out = new BufferedOutputStream(new FileOutputStream(file));

        CopyUtils.copy(in, out);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:com.intellij.tasks.impl.httpclient.ResponseUtil.java

public static Reader getResponseContentAsReader(@Nonnull HttpMethod response) throws IOException {
    //if (!response.hasBeenUsed()) {
    //  return new StringReader("");
    //}/*  w  w  w.  j a  v a 2s  .co  m*/
    InputStream stream = response.getResponseBodyAsStream();
    String charsetName = null;
    org.apache.commons.httpclient.Header header = response.getResponseHeader(HTTP.CONTENT_TYPE);
    if (header != null) {
        // find out encoding
        for (HeaderElement part : header.getElements()) {
            NameValuePair pair = part.getParameterByName("charset");
            if (pair != null) {
                charsetName = pair.getValue();
            }
        }
    }
    return new InputStreamReader(stream, charsetName == null ? DEFAULT_CHARSET_NAME : charsetName);
}

From source file:com.renlg.util.NetAssist.java

public static String delegateGet(String url) {

    StringBuffer response = new StringBuffer();
    HttpClient client = new HttpClient();
    HttpMethod method = null;
    try {//w w  w .j  a va  2 s .c  o m
        method = new GetMethod(url);
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(method.getResponseBodyAsStream(), "utf8"));
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
        }

    } catch (Exception e) {
        log.error("HTTP Get" + url + "??", e);
    } finally {
        if (method != null)
            method.releaseConnection();
    }
    return response.toString();
}

From source file:edu.du.penrose.systems.util.HttpClientUtils.java

/**
 * Appends response form URL to a StringBuffer
 * /*from  w  ww  .j  a  v a2  s.c om*/
 * @param requestUrl
 * @param resultStringBuffer
 * @return int request status code OR -1 if an exception occurred
 */
static public int getAsString(String requestUrl, StringBuffer resultStringBuffer) {
    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 {
        client.executeMethod(method);
        InputStream is = method.getResponseBodyAsStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        String datastr = null;
        byte[] bytes = new byte[8192]; // reading as chunk of 8192 bytes
        int count = bis.read(bytes);
        while (count != -1 && count <= 8192) {
            datastr = new String(bytes, 0, count);
            resultStringBuffer.append(datastr);
            count = bis.read(bytes);
        }
        bis.close();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }

    return method.getStatusCode();
}

From source file:com.cloud.test.longrun.PerformanceWithAPI.java

private static int CreateForwardingRule(User myUser, String privateIp, String publicIp, String publicPort,
        String privatePort) throws IOException {
    String encodedPrivateIp = URLEncoder.encode("" + privateIp, "UTF-8");
    String encodedPublicIp = URLEncoder.encode("" + publicIp, "UTF-8");
    String encodedPrivatePort = URLEncoder.encode("" + privatePort, "UTF-8");
    String encodedPublicPort = URLEncoder.encode("" + publicPort, "UTF-8");
    String encodedApiKey = URLEncoder.encode(myUser.getApiKey(), "UTF-8");
    int responseCode = 500;

    String requestToSign = "apiKey=" + encodedApiKey + "&command=createOrUpdateIpForwardingRule&privateIp="
            + encodedPrivateIp + "&privatePort=" + encodedPrivatePort + "&protocol=tcp&publicIp="
            + encodedPublicIp + "&publicPort=" + encodedPublicPort;

    requestToSign = requestToSign.toLowerCase();
    s_logger.info("Request to sign is " + requestToSign);

    String signature = TestClientWithAPI.signRequest(requestToSign, myUser.getSecretKey());
    String encodedSignature = URLEncoder.encode(signature, "UTF-8");

    String url = myUser.getDeveloperServer() + "?command=createOrUpdateIpForwardingRule" + "&publicIp="
            + encodedPublicIp + "&publicPort=" + encodedPublicPort + "&privateIp=" + encodedPrivateIp
            + "&privatePort=" + encodedPrivatePort + "&protocol=tcp&apiKey=" + encodedApiKey + "&signature="
            + encodedSignature;/*  www .  j a va  2  s  .c o  m*/

    s_logger.info("Trying to create IP forwarding rule: " + url);
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    responseCode = client.executeMethod(method);
    s_logger.info("create ip forwarding rule response code: " + responseCode);
    if (responseCode == 200) {
        s_logger.info("The rule is created successfully");
    } else if (responseCode == 500) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> errorInfo = TestClientWithAPI.getSingleValueFromXML(is,
                new String[] { "errorCode", "description" });
        s_logger.error("create ip forwarding rule (linux) test failed with errorCode: "
                + errorInfo.get("errorCode") + " and description: " + errorInfo.get("description"));
    } else {
        s_logger.error("internal error processing request: " + method.getStatusText());
    }
    return responseCode;
}