在后台程序中發送http請求並獲取響應數據


一,在后台程序中發送http請求獲取響應數據

  1)以 http://libs.baidu.com/jquery/2.0.0/jquery.min.js 為例

二,

  1)添加utf-8解決亂碼問題

     String result="";
        BufferedReader in = null;
        URL url = null;
        try {
            url = new URL("http://libs.baidu.com/jquery/2.0.0/jquery.min.js");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        //打開連接
        URLConnection connection = url.openConnection();

      // 設置通用的請求屬性
      connection.setRequestProperty("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,

      image/webp,image/apng,*/*;q=0.8");

      connection.setRequestProperty("accept-language", "zh-CN,zh;q=0.9");
      connection.setRequestProperty("cache-control", "max-age=0");
      connection.setRequestProperty("connection", "Keep-Alive");
      connection.setRequestProperty("Accept-Charset", "UTF-8");
      connection.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36

      (KHTML, like Gecko) Chrome/62.0.3202.      89 Safari/537.36");
      // 建立實際的連接
      connection.connect();

      // 定義 BufferedReader輸入流來讀取URL的響應
      in = new BufferedReader(new InputStreamReader(
      connection.getInputStream(),"UTF-8"));


        //寫出數據
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        //關流
        in.close();
        System.out.println(result);

三,


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM