Example usage for org.apache.commons.httpclient HttpClient HttpClient

List of usage examples for org.apache.commons.httpclient HttpClient HttpClient

Introduction

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

Prototype

public HttpClient() 

Source Link

Usage

From source file:ClientPost.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod("http://localhost:8080/home/viewPost.jsp");
    NameValuePair[] postData = { new NameValuePair("username", "devgal"),
            new NameValuePair("department", "development"), new NameValuePair("email", "devgal@yahoo.com") };
    //the 2.0 beta1 version has a
    // PostMethod.setRequestBody(NameValuePair[])
    //method, as addParameters is deprecated
    postMethod.addParameters(postData);/*  w  ww  .  j a  v  a2 s  .c om*/
    httpClient.executeMethod(postMethod);
    //display the response to the POST method
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    //A "200 OK" HTTP Status Code
    if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
        out.println(postMethod.getResponseBodyAsString());
    } else {
        out.println("The POST action raised an error: " + postMethod.getStatusLine());
    }
    //release the connection used by the method
    postMethod.releaseConnection();

}

From source file:com.kwoksys.framework.util.HttpUtils.java

/**
 * Gets contents from url//w  w  w  .  j a  v a2  s  . com
 * @param url
 * @return
 * @throws Exception
 */
public static String getContent(String url) throws Exception {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            throw new Exception("HTTP method error: " + method.getStatusLine());
        }

        // Read the response body.
        return new String(method.getResponseBody());

    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:jshm.sh.Client.java

public static HttpClient getHttpClient() {
    if (null == httpClient) {
        httpClient = new HttpClient();
    }

    return httpClient;
}

From source file:com.mycompany.semconsolewebapp.FileUpload.java

public static void uploadImage(String urlString, Part[] parts) throws FileNotFoundException, IOException {
    PostMethod postMessage = new PostMethod(urlString);
    postMessage.setRequestEntity(new MultipartRequestEntity(parts, postMessage.getParams()));
    HttpClient client = new HttpClient();

    int status = client.executeMethod(postMessage);
    System.out.println("Got status message " + status);
}

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

/**
 * Appends response form URL to a StringBuffer
 * /*w  ww .  java2s  .c o m*/
 * @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:at.gv.egovernment.moa.id.commons.utils.HttpClientWithProxySupport.java

public static HttpClient getHttpClient() {
    HttpClient client = new HttpClient();

    String host = System.getProperty("http.proxyHost"); //$NON-NLS-1$
    String port = System.getProperty("http.proxyPort"); //$NON-NLS-1$
    if (MiscUtil.isNotEmpty(host) && MiscUtil.isNotEmpty(port)) {
        int p = Integer.parseInt(port);
        client.getHostConfiguration().setProxy(host, p);
        Logger.info("Initial HTTPClient with proxy usage. " + "ProxyHost=" + host + " ProxyPort=" + port);

        String user = System.getProperty("http.proxyUser"); //$NON-NLS-1$
        String pass = System.getProperty("http.proxyPassword"); //$NON-NLS-1$
        if (MiscUtil.isNotEmpty(user) && pass != null) {
            client.getState().setProxyCredentials(new AuthScope(host, p),
                    new UsernamePasswordCredentials(user, pass));

        }/*  ww  w . j  av  a 2  s  .  c  o m*/
    }
    return client;
}

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);/*from   w  ww.ja  va2  s  .  c  o m*/

    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.cloudbees.api.HttpClientHelper.java

public static HttpClient createClient(BeesClientConfiguration beesClientConfiguration) {
    HttpClient client = new HttpClient();
    String proxyHost = beesClientConfiguration.getProxyHost();
    if (proxyHost != null) {
        int proxyPort = beesClientConfiguration.getProxyPort();

        client.getHostConfiguration().setProxy(proxyHost, proxyPort);

        //if there are proxy credentials available, set those too
        Credentials proxyCredentials = null;
        String proxyUser = beesClientConfiguration.getProxyUser();
        String proxyPassword = beesClientConfiguration.getProxyPassword();
        if (proxyUser != null || proxyPassword != null)
            proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
        if (proxyCredentials != null)
            client.getState().setProxyCredentials(AuthScope.ANY, proxyCredentials);
    }/*from   w w w.j  a  va2s  .  co m*/

    return client;
}

From source file:apm.common.utils.HttpTookit.java

/**
 * HTTP GET?HTML//  w  w w . j a  v a  2s  .  c o m
 * 
 * @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:com.robonobo.common.media.PlaylistItem.java

public static List getPlaylist(String uri) throws IOException, PlaylistFormatException {
    Log log = LogFactory.getLog(PlaylistItem.class);
    Vector list = new Vector();
    HttpClient client = new HttpClient();
    GetMethod get = new GetMethod(uri);
    int status = client.executeMethod(get);
    switch (status) {
    case 200://from  w  w  w .j  a  v  a 2 s.c  om
        BufferedReader reader = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream()));
        String line = reader.readLine();
        if (!line.equals("[playlist]"))
            throw new PlaylistFormatException("The provided URL does not describe a playlist");
        String[] kvp;
        int currentEntryNumber = 1;
        int version = 2;
        int supposedNumberOfEntries = 1;
        PlaylistItem currentEntry = new PlaylistItem();
        while ((line = reader.readLine()) != null) {
            kvp = line.split("=");
            if (kvp[0].equals("NumberOfEntries")) {
                supposedNumberOfEntries = Integer.parseInt(kvp[1]);
            } else if (kvp[0].equals("Version")) {
                version = Integer.parseInt(kvp[1]);
                if (version != 2)
                    throw new PlaylistFormatException(
                            "This parser currently only supports version 2 .pls files");
            } else {
                if (!kvp[0].endsWith(String.valueOf(currentEntryNumber))) {
                    list.add(currentEntry);
                    currentEntryNumber++;
                    currentEntry = new PlaylistItem();
                }
                if (kvp[0].startsWith("File")) {
                    currentEntry.setFile(kvp[1]);
                } else if (kvp[0].startsWith("Title")) {
                    currentEntry.setTitle(kvp[1]);
                } else if (kvp[0].startsWith("Length")) {
                    currentEntry.setLength(Integer.parseInt(kvp[1]));
                }
            }
        }
        if (currentEntry != null)
            list.add(currentEntry);
        if (supposedNumberOfEntries != list.size())
            throw new PlaylistFormatException("The server said there were " + supposedNumberOfEntries
                    + " but we actually got " + list.size());
        return list;
    default:
        throw new IOException(
                "The remote server responded with a status " + status + " and not 200 as expected");
    }
}