Example usage for org.apache.http.client.methods HttpGet HttpGet

List of usage examples for org.apache.http.client.methods HttpGet HttpGet

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpGet HttpGet.

Prototype

public HttpGet(final String uri) 

Source Link

Usage

From source file:Main.java

/**
 * Code adapted from http://stackoverflow.com/a/12854981
 * @return Device external IP address or ERROR statement.
 *//*from  w  ww.j av a 2 s. c  o  m*/
public static String getExternalIP() {
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://ip2country.sourceforge.net/ip2c.php?format=JSON");
        // HttpGet httpget = new HttpGet("http://whatismyip.com.au/");
        // HttpGet httpget = new HttpGet("http://www.whatismyip.org/");
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        if (entity != null && entity.getContentLength() > 0) {
            JSONObject json_data = new JSONObject(EntityUtils.toString(entity));
            return json_data.getString("ip");
        } else {
            Log.e(LOG_TAG, "Response error: " + response.getStatusLine().toString());
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, e.toString());
    }
    return "ERROR";
}

From source file:Main.java

public static boolean getkeepaliveinfo() {
    String baseUrl = "http://10.6.8.2/cgi-bin/keeplive?";

    try {//w ww. j  ava  2s . c om
        HttpGet getMethod = new HttpGet(baseUrl);
        getMethod.addHeader("Accept", "*/*");
        //getMethod.addHeader("Accept-Language", "zh-cn");
        //getMethod.addHeader("Referer", "http://202.117.2.41/index.html");
        //getMethod.addHeader("Content-Type", "application/x-www-form-urlencoded");
        //getMethod.addHeader("Accept-Encoding", "gzip, deflate");
        //getMethod.addHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)");
        getMethod.addHeader("Host", "10.6.8.2");
        //getMethod.addHeader("DNT", "1");

        HttpClient httpClient = new DefaultHttpClient();

        HttpResponse response = httpClient.execute(getMethod);
        Log.i(TAG, "Sending message.....");
        HttpEntity httpEntity = response.getEntity();
        if (response.getStatusLine().getStatusCode() == 200) {
            String message = EntityUtils.toString(httpEntity);
            if (httpEntity == null || message.compareTo("error") == 0) {
                Log.i(TAG, "Get keepalive info failed!!!message=" + message);
                return false;
            } else {
                Log.i(TAG, "Get keepalive info succeed!!!message=" + message);
                return true;
            }
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.i(TAG, "Get keepalive info failed!!!");
    return false;
}

From source file:Main.java

public static boolean logout() {
    String baseUrl = "http://10.6.8.2/cgi-bin/srun_portal?action=logout&ac_id=1";

    try {//from   ww  w . ja v a  2 s  . co  m
        HttpGet getMethod = new HttpGet(baseUrl);
        getMethod.addHeader("Accept", "*/*");
        //getMethod.addHeader("Accept-Language", "zh-cn");
        //getMethod.addHeader("Referer", "http://202.117.2.41/index.html");
        //getMethod.addHeader("Content-Type", "application/x-www-form-urlencoded");
        //getMethod.addHeader("Accept-Encoding", "gzip, deflate");
        //getMethod.addHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)");
        getMethod.addHeader("Host", "10.6.8.2");
        //getMethod.addHeader("DNT", "1");

        HttpClient httpClient = new DefaultHttpClient();

        HttpResponse response = httpClient.execute(getMethod);
        Log.i(TAG, "Sending message.....");
        HttpEntity httpEntity = response.getEntity();
        if (response.getStatusLine().getStatusCode() == 200) {
            String message = EntityUtils.toString(httpEntity);
            Log.i(TAG, "Logout succeed!!! message=" + message);
            return true;
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.i(TAG, "Logout failed!!!");
    return false;
}

From source file:Main.java

public static String getJson(String url) throws ClientProtocolException, IOException, InterruptedException {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    HttpResponse response = client.execute(httpGet);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;/* www . j  a va 2s .  c  o m*/
        while ((line = reader.readLine()) != null)
            builder.append(line);
    }
    return builder.toString();
}

From source file:Main.java

/**
 * fetch JSONArray from given url, must be called on worker thread
 * @param url//from   w  ww .  j  a va  2s  . c o m
 * @return
 * @throws JSONException
 * @throws IOException
 */
public static JSONArray getRemoteJsonArray(String url) throws JSONException, IOException {
    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);
    HttpResponse response = client.execute(get);
    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuilder builder = new StringBuilder();
    for (String s = reader.readLine(); s != null; s = reader.readLine()) {
        builder.append(s);
    }
    return new JSONArray(builder.toString());
}

From source file:Main.java

public static Bitmap getGoogleMapThumbnail(double latitude, double longitude) {
    String URL = "http://maps.google.com/maps/api/staticmap?center=" + latitude + "," + longitude
            + "&zoom=15&size=600x600&sensor=false";

    Bitmap bmp = null;//from w  w w  .  jav a 2s . c  om
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet request = new HttpGet(URL);

    InputStream in = null;
    try {
        in = httpclient.execute(request).getEntity().getContent();
        bmp = BitmapFactory.decodeStream(in);
        in.close();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return bmp;
}

From source file:com.boonya.http.async.examples.nio.client.AsyncClientConfiguration.java

public final static void main(String[] args) throws Exception {

    // Use custom message parser / writer to customize the way HTTP
    // messages are parsed from and written out to the data stream.
    NHttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {

        @Override/*  w ww. jav  a 2s .c o  m*/
        public NHttpMessageParser<HttpResponse> create(final SessionInputBuffer buffer,
                final MessageConstraints constraints) {
            LineParser lineParser = new BasicLineParser() {

                @Override
                public Header parseHeader(final CharArrayBuffer buffer) {
                    try {
                        return super.parseHeader(buffer);
                    } catch (ParseException ex) {
                        return new BasicHeader(buffer.toString(), null);
                    }
                }

            };
            return new DefaultHttpResponseParser(buffer, lineParser, DefaultHttpResponseFactory.INSTANCE,
                    constraints);
        }

    };
    NHttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();

    // Use a custom connection factory to customize the process of
    // initialization of outgoing HTTP connections. Beside standard connection
    // configuration parameters HTTP connection factory can define message
    // parser / writer routines to be employed by individual connections.
    NHttpConnectionFactory<ManagedNHttpClientConnection> connFactory = new ManagedNHttpClientConnectionFactory(
            requestWriterFactory, responseParserFactory, HeapByteBufferAllocator.INSTANCE);

    // Client HTTP connection objects when fully initialized can be bound to
    // an arbitrary network socket. The process of network socket initialization,
    // its connection to a remote address and binding to a local one is controlled
    // by a connection socket factory.

    // SSL context for secure connections can be created either based on
    // system or application specific properties.
    SSLContext sslcontext = SSLContexts.createSystemDefault();
    // Use custom hostname verifier to customize SSL hostname verification.
    HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();

    // Create a registry of custom connection session strategies for supported
    // protocol schemes.
    Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder
            .<SchemeIOSessionStrategy>create().register("http", NoopIOSessionStrategy.INSTANCE)
            .register("https", new SSLIOSessionStrategy(sslcontext, hostnameVerifier)).build();

    // Use custom DNS resolver to override the system DNS resolution.
    DnsResolver dnsResolver = new SystemDefaultDnsResolver() {

        @Override
        public InetAddress[] resolve(final String host) throws UnknownHostException {
            if (host.equalsIgnoreCase("myhost")) {
                return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
            } else {
                return super.resolve(host);
            }
        }

    };

    // Create I/O reactor configuration
    IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
            .setIoThreadCount(Runtime.getRuntime().availableProcessors()).setConnectTimeout(30000)
            .setSoTimeout(30000).build();

    // Create a custom I/O reactort
    ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);

    // Create a connection manager with custom configuration.
    PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor,
            connFactory, sessionStrategyRegistry, dnsResolver);

    // Create message constraints
    MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
            .setMaxLineLength(2000).build();
    // Create connection configuration
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(messageConstraints).build();
    // Configure the connection manager to use connection configuration either
    // by default or for a specific host.
    connManager.setDefaultConnectionConfig(connectionConfig);
    connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    connManager.setMaxTotal(100);
    connManager.setDefaultMaxPerRoute(10);
    connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);

    // Use custom cookie store if necessary.
    CookieStore cookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    // Create global request configuration
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT)
            .setExpectContinueEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();

    // Create an HttpClient with the given custom dependencies and configuration.
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setConnectionManager(connManager)
            .setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credentialsProvider)
            .setProxy(new HttpHost("myproxy", 8080)).setDefaultRequestConfig(defaultRequestConfig).build();

    try {
        HttpGet httpget = new HttpGet("http://localhost/");
        // Request configuration can be overridden at the request level.
        // They will take precedence over the one set at the client level.
        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(5000)
                .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                .setProxy(new HttpHost("myotherproxy", 8080)).build();
        httpget.setConfig(requestConfig);

        // Execution context can be customized locally.
        HttpClientContext localContext = HttpClientContext.create();
        // Contextual attributes set the local context level will take
        // precedence over those set at the client level.
        localContext.setCookieStore(cookieStore);
        localContext.setCredentialsProvider(credentialsProvider);

        System.out.println("Executing request " + httpget.getRequestLine());

        httpclient.start();

        // Pass local context as a parameter
        Future<HttpResponse> future = httpclient.execute(httpget, localContext, null);

        // Please note that it may be unsafe to access HttpContext instance
        // while the request is still being executed

        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());

        // Once the request has been executed the local context can
        // be used to examine updated state and various objects affected
        // by the request execution.

        // Last executed request
        localContext.getRequest();
        // Execution route
        localContext.getHttpRoute();
        // Target auth state
        localContext.getTargetAuthState();
        // Proxy auth state
        localContext.getTargetAuthState();
        // Cookie origin
        localContext.getCookieOrigin();
        // Cookie spec used
        localContext.getCookieSpec();
        // User security token
        localContext.getUserToken();
    } finally {
        httpclient.close();
    }
}

From source file:Main.java

public static String GET(String url) {
    InputStream inputStream = null;
    String result = "";
    try {// w  w w. j av a  2 s  .  c om

        // create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // make GET request to the given URL
        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

        // receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // convert inputstream to string
        if (inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    return result;
}

From source file:Main.java

protected static synchronized InputStream getAWebPage(URL url) throws ClientProtocolException, IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(url.toString());
    try {//from   ww w. j  av  a2 s  . c o  m
        //do the request
        HttpResponse response = httpClient.execute(httpGet, localContext);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != HTTP_STATUS_OK) {
            throw new IOException("Invalid response from the IKSU server! " + status.toString());
        }
        //InputStream ist = response.getEntity().getContent();

        return response.getEntity().getContent();
    } catch (Exception e) {
        e.printStackTrace();
        throw new ClientProtocolException("Protocol Exception! " + e.toString());
    }
}

From source file:Main.java

public static String downloadPage(String url) {
    Log.v(DEBUG_TAG, url);/*from  w w w . ja  v a2 s .com*/

    String page = "";

    BufferedReader in = null;
    try {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        HttpParams params = request.getParams();
        HttpConnectionParams.setSoTimeout(params, 60000); // 1 minute timeout               
        HttpResponse response = client.execute(request);

        //Predifined buffer size
        /*
         * 
        in = new BufferedReader(
            new InputStreamReader(
           response.getEntity().getContent()),8*2000);
         * 
         * */

        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";
        //String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
        in.close();
        page = sb.toString();
        Log.v(DEBUG_TAG, "Pagina descargada --> " + page);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                Log.v(DEBUG_TAG, "Error en la descarga de la pagina");
                e.printStackTrace();
            }
        }
    }
    return page;
}