Example usage for org.apache.http.impl.client DefaultHttpClient execute

List of usage examples for org.apache.http.impl.client DefaultHttpClient execute

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient execute.

Prototype

public CloseableHttpResponse execute(final HttpUriRequest request, final HttpContext context)
        throws IOException, ClientProtocolException 

Source Link

Usage

From source file:simple.crawler.ext.vanilla.VanillaForumUtil.java

public static int postDiscussion(HttpContext httpContext, String postURL, String title, String body)
        throws Exception {
    DefaultHttpClient httpclient = HttpClientFactory.getInstance();
    HttpResponse res = httpclient.execute(new HttpGet(postURL), httpContext);
    String html = HttpClientUtil.getContentBodyAsString(res);
    HtmlParser parser = new HtmlParser();
    Document doc = parser.parseNonWellForm(html);
    Node node = (Node) XPathUtil.read(doc, "//*[@id=\"Form_TransientKey\"]", XPathConstants.NODE);
    String postTransientKey = ((Element) node).getAttribute("value");

    HttpPost post = new HttpPost(postURL);
    List<NameValuePair> list = new ArrayList<NameValuePair>();
    list.add(new BasicNameValuePair("Discussion/TransientKey", postTransientKey));
    list.add(new BasicNameValuePair("Discussion/Name", title));
    list.add(new BasicNameValuePair("Discussion/Body", body));
    list.add(new BasicNameValuePair("Discussion/Post_Discussion", "Post Discussion"));
    post.setEntity(new UrlEncodedFormEntity(list));
    res = httpclient.execute(post, httpContext);
    return res.getStatusLine().getStatusCode();
}

From source file:neembuu.release1.httpclient.utils.NHttpClientUtils.java

/**
 * Get the content of a page./*from ww w .  j a va  2s .com*/
 * @param url url from which to read
 * @param httpContext the httpContext in which to make the request
 * @return the String content of the page
 * @throws Exception 
 */
public static String getData(String url, HttpContext httpContext, DefaultHttpClient httpClient)
        throws Exception {
    HttpGet httpGet = new HttpGet(url);
    HttpResponse httpResponse = httpClient.execute(httpGet, httpContext);
    return EntityUtils.toString(httpResponse.getEntity());
}

From source file:com.kku.apps.pricesearch.util.HttpConnection.java

public static Bitmap getBitmapFromUrl(String url) {

    HttpGet method = new HttpGet(url);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {/*from  w ww  .  ja v a2  s .co m*/
        BufferedHttpEntity entity = httpClient.execute(method, new ResponseHandler<BufferedHttpEntity>() {

            @Override
            public BufferedHttpEntity handleResponse(HttpResponse response)
                    throws ClientProtocolException, IOException {

                // Xe?[^XR?[h
                int status = response.getStatusLine().getStatusCode();

                if (HttpStatus.SC_OK != status) {
                    throw new RuntimeException("?MG?[?");
                }
                HttpEntity entity = response.getEntity();
                BufferedHttpEntity bufferEntity = new BufferedHttpEntity(entity);
                return bufferEntity;
            }
        });
        InputStream is = entity.getContent();
        return BitmapFactory.decodeStream(is);
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.silvertunnel.netlib.adapter.httpclient.HttpClientUtil.java

private static InputStream action_NOT_NEEDED(URL url) throws IOException {

    HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

    DefaultHttpClient httpclient = new DefaultHttpClient(connMgr, params);

    HttpGet req = new HttpGet(url.getPath());

    log.info("executing request to " + target);

    HttpResponse rsp = httpclient.execute(target, req);
    HttpEntity entity = rsp.getEntity();
    /*/*from ww  w . ja  v  a 2 s.  co  m*/
    if (entity != null) {
    log.info(EntityUtils.toString(entity));
    }
    */
    return entity.getContent();

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources

    //TODO: httpclient.getConnectionManager().shutdown();        

}

From source file:net.sf.dvstar.transmission.protocol.TestConnection.java

public static void testConnection() throws Exception {
    // make sure to use a proxy that supports CONNECT
    HttpHost target = new HttpHost("195.74.67.237", 80, "http");
    HttpHost proxy = new HttpHost("192.168.4.7", 3128, "http");

    // general setup
    SchemeRegistry supportedSchemes = new SchemeRegistry();

    // Register the "http" and "https" protocol schemes, they are
    // required by the default operator to look up socket factories.
    supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, true);

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes);

    DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params);

    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    HttpGet req = new HttpGet("/");

    System.out.println("executing request to " + target + " via " + proxy);
    HttpResponse rsp = httpclient.execute(target, req);
    HttpEntity entity = rsp.getEntity();

    System.out.println("----------------------------------------");
    System.out.println(rsp.getStatusLine());
    Header[] headers = rsp.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        System.out.println(headers[i]);
    }//from ww w. ja va  2s  .c  om
    System.out.println("----------------------------------------");

    if (entity != null) {
        System.out.println(EntityUtils.toString(entity));
    }

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

From source file:simple.crawler.ext.vanilla.VanillaForumUtil.java

public static HttpContext login(String loginURL, String username, String password) throws Exception {
    DefaultHttpClient httpclient = HttpClientFactory.getInstance();
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    HttpResponse res = httpclient.execute(new HttpGet(loginURL), httpContext);

    String html = HttpClientUtil.getContentBodyAsString(res);
    HtmlParser parser = new HtmlParser();
    Document doc = parser.parseNonWellForm(html);

    ///*from  w  w w . j  a va  2 s. c om*/
    Node loginTransientKey = (Node) XPathUtil.read(doc, "//*[@id=\"Form_TransientKey\"]", XPathConstants.NODE);
    Node hpt = (Node) XPathUtil.read(doc, "//*[@id=\"Form_hpt\"]", XPathConstants.NODE);
    Node target = (Node) XPathUtil.read(doc, "//*[@id=\"Form_Target\"]", XPathConstants.NODE);
    Node clientHour = (Node) XPathUtil.read(doc, "//*[@id=\"Form_ClientHour\"]", XPathConstants.NODE);

    //
    List<NameValuePair> list = new ArrayList<NameValuePair>();
    list.add(new BasicNameValuePair("Form/TransientKey", ((Element) loginTransientKey).getAttribute("value")));
    list.add(new BasicNameValuePair("Form/hpt", ((Element) hpt).getAttribute("value")));
    list.add(new BasicNameValuePair("Form/Target", ((Element) target).getAttribute("value")));
    list.add(new BasicNameValuePair("Form/ClientHour", ((Element) clientHour).getAttribute("value")));
    list.add(new BasicNameValuePair("Form/Email", "admin"));
    list.add(new BasicNameValuePair("Form/Password", "admin"));
    list.add(new BasicNameValuePair("Form/Sign_In", "Sign In"));
    list.add(new BasicNameValuePair("Form/RememberMe", "1"));
    list.add(new BasicNameValuePair("Checkboxes[]", "RememberMe"));

    HttpPost post = new HttpPost(loginURL);
    post.setEntity(new UrlEncodedFormEntity(list));
    res = httpclient.execute(post, httpContext);
    return httpContext;
}

From source file:com.google.resting.rest.client.impl.RESTClient.java

/**
 * Executes secure SSL request using HTTPS
 * //  w  w w . j av  a2  s .c o m
 * @param Domain of the REST endpoint
 * @param path Path of the URI
 * @param port port number of the REST endpoint
 * @param verb Type of HTTP method(GET/POST/PUT/DELETE)
 * 
 * @return ServiceResponse object containing http status code and entire response as a String
 */
public static ServiceResponse secureInvoke(ServiceContext serviceContext) {
    String targetDomain = serviceContext.getTargetDomain();
    int port = serviceContext.getPort();
    ServiceResponse serviceResponse = null;
    EncodingTypes charset = serviceContext.getCharset();
    try {
        long ioStartTime = System.currentTimeMillis();
        HttpHost targetHost = new HttpHost(targetDomain, port, RequestConstants.HTTPS);
        HttpRequest request = buildHttpRequest(serviceContext);

        DefaultHttpClient httpclient = buildHttpClient(serviceContext);
        httpclient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme(RequestConstants.HTTPS, new CustomSSLSocketFactory(), port));

        HttpResponse response = httpclient.execute(targetHost, request);
        serviceResponse = new ServiceResponse(response, charset);
        long ioEndTime = System.currentTimeMillis();

        System.out.println("Time taken in executing REST: " + (ioEndTime - ioStartTime));

    } catch (Exception e) {
        e.printStackTrace();
    }

    return serviceResponse;

}

From source file:org.android.CPForAndroidPlusPlus.HttpClient.java

public static String makeRequest(String path) throws Exception {
    final String TAG = "HttpClient"; //Used in logging etc.
    String str = "";

    try {/*from w  ww  . j  a v  a 2  s . co  m*/
        DefaultHttpClient httpclient = new DefaultHttpClient();
        //HttpParams params = new BasicHttpParams();
        //params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000L);
        //httpclient.setParams(params);
        HttpGet httpost = new HttpGet(path);

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        str = (String) httpclient.execute(httpost, responseHandler);
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }
    return str;
}

From source file:com.oakley.fon.util.HttpUtils.java

public static HttpResult getUrl(String url, int maxRetries) throws IOException {
    String result = null;//from   w w  w .j  a  v  a 2  s .  c o  m
    int retries = 0;
    HttpContext localContext = new BasicHttpContext();
    DefaultHttpClient httpclient = getHttpClient();

    HttpGet httpget = new HttpGet(url);
    while (retries <= maxRetries && result == null) {
        try {
            retries++;
            HttpEntity entity = httpclient.execute(httpget, localContext).getEntity();

            if (entity != null) {
                result = EntityUtils.toString(entity).trim();
            }
        } catch (SocketException se) {
            if (retries > maxRetries) {
                throw se;
            } else {
                Log.v(TAG, "SocketException, retrying " + retries);
            }
        }
    }

    return new HttpResult(result, (BasicHttpResponse) localContext.getAttribute("http.response"),
            ((HttpHost) localContext.getAttribute("http.target_host")).toURI());
}

From source file:com.codebutler.rsp.Util.java

public static String getURL(URL url, String password) throws Exception {
    Log.i("Util.getURL", url.toString());

    DefaultHttpClient client = new DefaultHttpClient();

    if (password != null && password.length() > 0) {
        UsernamePasswordCredentials creds;
        creds = new UsernamePasswordCredentials("user", password);
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
    }//from  www. j  av a2 s . c om

    HttpGet method = new HttpGet(url.toURI());
    BasicResponseHandler responseHandler = new BasicResponseHandler();
    return client.execute(method, responseHandler);
}