Java如何调用HttpURLConnection类模拟浏览器访问呢?

打印 上一主题 下一主题

主题 871|帖子 871|积分 2613

下文笔者讲述使用Java代码模拟浏览器请求的方法分享,如下所示:
  1. <strong>实现思路:
  2.     使用HttpURLConnection类即可模拟浏览器访问
  3. </strong>
复制代码
例:
  1. package com.java265.other;
  2. import java.io.BufferedReader;
  3. import java.io.DataOutputStream;
  4. import java.io.InputStreamReader;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import java.net.URLEncoder;
  8. public class HttpURLConnectionTest {
  9.     public static final String GET_URL = "http://java265.com";
  10.     public static final String POST_URL = "http://java265.com";
  11.    
  12.     /**
  13.      * 接口调用 GET
  14.      */
  15.     public static void httpURLConectionGET() {
  16.         try {
  17.             URL url = new URL(GET_URL);    // 把字符串转换为URL请求地址
  18.             HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
  19.             connection.connect();// 连接会话
  20.             // 获取输入流
  21.             BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  22.             String line;
  23.             StringBuilder sb = new StringBuilder();
  24.             while ((line = br.readLine()) != null) {// 循环读取流
  25.                 sb.append(line);
  26.             }
  27.             br.close();// 关闭流
  28.             connection.disconnect();// 断开连接
  29.             System.out.println(sb.toString());
  30.         } catch (Exception e) {
  31.             e.printStackTrace();
  32.             System.out.println("失败!");
  33.         }
  34.     }
  35.    
  36.     /**
  37.      * 接口调用  POST
  38.      */
  39.     public static void httpURLConnectionPOST () {
  40.         try {
  41.             URL url = new URL(POST_URL);
  42.            
  43.             // 将url 以 open方法返回的urlConnection  连接强转为HttpURLConnection连接  (标识一个url所引用的远程对象连接)
  44.             HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 此时cnnection只是为一个连接对象,待连接中
  45.            
  46.             // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
  47.             connection.setDoOutput(true);
  48.            
  49.             // 设置连接输入流为true
  50.             connection.setDoInput(true);
  51.            
  52.             // 设置请求方式为post
  53.             connection.setRequestMethod("POST");
  54.            
  55.             // post请求缓存设为false
  56.             connection.setUseCaches(false);
  57.            
  58.             // 设置该HttpURLConnection实例是否自动执行重定向
  59.             connection.setInstanceFollowRedirects(true);
  60.            
  61.             // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
  62.             // application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据
  63.             connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  64.            
  65.             // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
  66.             connection.connect();
  67.            
  68.             // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
  69.             DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
  70.             String parm = "storeId=" + URLEncoder.encode("32", "utf-8"); //URLEncoder.encode()方法  为字符串进行编码
  71.            
  72.             // 将参数输出到连接
  73.             dataout.writeBytes(parm);
  74.            
  75.             // 输出完成后刷新并关闭流
  76.             dataout.flush();
  77.             dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)
  78.            
  79.             System.out.println(connection.getResponseCode());
  80.            
  81.             // 连接发起请求,处理服务器响应  (从连接获取到输入流并包装为bufferedReader)
  82.             BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  83.             String line;
  84.             StringBuilder sb = new StringBuilder(); // 用来存储响应数据
  85.            
  86.             // 循环读取流,若不到结尾处
  87.             while ((line = bf.readLine()) != null) {
  88.                 sb.append(bf.readLine());
  89.             }
  90.             bf.close();    // 重要且易忽略步骤 (关闭流,切记!)
  91.             connection.disconnect(); // 销毁连接
  92.             System.out.println(sb.toString());
  93.    
  94.         } catch (Exception e) {
  95.             e.printStackTrace();
  96.         }
  97.     }
  98.    
  99.     public static void main(String[] args) {
  100.         httpURLConnectionPOST();
  101.     }
  102. }
复制代码
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

熊熊出没

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表