在后台程序中发送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);

三,

原文地址:https://www.cnblogs.com/hi-feng/p/8006750.html