get HTTP Request and set Connection property - Android Network

Android examples for Network:HTTP Request

Description

get HTTP Request and set Connection property

Demo Code


//package com.java2s;
import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class Main {
    public static String getRequest(final String url) throws Exception {
        FutureTask<String> task = new FutureTask<String>(
                new Callable<String>() {
                    @Override//ww w . ja v  a  2 s .  c  om
                    public String call() {
                        BufferedReader in = null;
                        String result = "";
                        try {

                            URL localurl = new URL(url);

                            URLConnection conn = localurl.openConnection();

                            conn.setRequestProperty("accept", "*/*");

                            conn.setRequestProperty("connection",
                                    "Keep-Alive");

                            conn.setRequestProperty("user-agent",
                                    "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");

                            conn.connect();

                            in = new BufferedReader(new InputStreamReader(
                                    conn.getInputStream()));

                            String line = "";

                            while ((line = in.readLine()) != null) {
                                result += line;
                            }

                            return result;
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                if (in != null) {
                                    in.close();
                                }
                            } catch (Exception e2) {
                                e2.printStackTrace();
                            }
                        }
                        return null;
                    }
                });
        new Thread(task).start();
        return task.get();
    }
}

Related Tutorials