1. 程式人生 > >java構造http請求

java構造http請求

####【在java後臺呼叫介面,傳送http請求獲取資料–GET】

public static void initmap(){
        //傳送http請求獲取用於初始化的資料
        BufferedReader in = null;
        String result="";
        try {
            System.out.println("正在獲取初始化所需資料---");
            URL url=new URL("http://localhost:1188/border/website/indexrecord");
            // 開啟和URL之間的連線
            URLConnection connection = url.openConnection();
            // 設定通用的請求屬性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立實際的連線
            connection.connect();
            // 定義 BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            List<Website> websiteList= ResultContent.ResultStringtoList(result);
            System.out.println("資料獲取成功-----正在初始化----");
            for(int i=0;i<websiteList.size();i++){
                map.put(websiteList.get(i).getKeynum(),websiteList.get(i).getCounts());
            }
            System.out.println(map);
            System.out.println("計數執行緒初始化完畢");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("請求初始化所需資料失敗++");
            e.printStackTrace();
        }finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

####【請求資料包含在url中】

public static void TimerUpdatemysql(Long counts,Long keynum){
        //傳送http請求獲取用於初始化的資料
        try {
            System.out.println("正在更新資料庫---");
            String updateurl="http://localhost:1188/border/website/updatecounts?counts="+counts+"&keynum="+keynum;
            System.out.println(updateurl);
            URL url=new URL(updateurl);
            // 開啟和URL之間的連線
            URLConnection connection = url.openConnection();
            // 設定通用的請求屬性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立實際的連線
            connection.connect();
            System.out.println("資料已更新");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("儲存資料庫失敗++");
            e.printStackTrace();
        }
    }