zoukankan      html  css  js  c++  java
  • java模拟浏览器发送请求

      1 package test;
      2 
      3 import java.io.BufferedReader;
      4 import java.io.DataOutputStream;
      5 import java.io.IOException;
      6 import java.io.InputStreamReader;
      7 import java.net.HttpURLConnection;
      8 import java.net.URL;
      9 import java.net.URLEncoder;
     10 
     11 import javax.servlet.http.HttpServletRequest;
     12 
     13 import org.apache.http.HttpEntity;
     14 import org.apache.http.HttpResponse;
     15 import org.apache.http.client.ClientProtocolException;
     16 import org.apache.http.client.methods.HttpGet;
     17 import org.apache.http.client.methods.HttpPost;
     18 import org.apache.http.client.utils.HttpClientUtils;
     19 import org.apache.http.entity.StringEntity;
     20 import org.apache.http.impl.client.DefaultHttpClient;
     21 import org.apache.http.util.EntityUtils;
     22 
     23 public class TestRequestUtil {
     24 //    public static void main(String[] args) {
     25 //        doGetStr("http://dzdzwxcs1.ciitc.com.cn/s/VcbrYFtK");
     26 //    }
     27     /**
     28      * 接口调用 GET
     29      */
     30     public static void httpURLConectionGET(String urls) {
     31         try {
     32             URL url = new URL(urls); // 把字符串转换为URL请求地址
     33             HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
     34             connection.connect();// 连接会话
     35             // 获取输入流
     36             BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
     37             String line;
     38             StringBuilder sb = new StringBuilder();
     39             while ((line = br.readLine()) != null) {// 循环读取流
     40                 sb.append(line);    //写入对象中
     41             }
     42             br.close();// 关闭流
     43             connection.disconnect();// 断开连接
     44             System.out.println(sb.toString());
     45         } catch (Exception e) {
     46             e.printStackTrace();
     47             System.out.println("请求失败!");
     48         }
     49     }
     50 
     51     /**
     52      * 接口调用 POST
     53      */
     54     public static void httpURLConnectionPOST(String urls) {
     55         try {
     56             URL url = new URL(urls);
     57 
     58             // 将url 以 open方法返回的urlConnection 连接强转为HttpURLConnection连接 (标识一个url所引用的远程对象连接)
     59             HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 此时cnnection只是为一个连接对象,待连接中
     60 
     61             // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
     62             connection.setDoOutput(true);
     63 
     64             // 设置连接输入流为true
     65             connection.setDoInput(true);
     66 
     67             // 设置请求方式为post
     68             connection.setRequestMethod("POST");
     69 
     70             // post请求缓存设为false
     71             connection.setUseCaches(false);
     72 
     73             // 设置该HttpURLConnection实例是否自动执行重定向
     74             connection.setInstanceFollowRedirects(true);
     75 
     76             // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
     77             // application/x-javascript text/xml->xml数据 application/x-javascript->json对象
     78             // application/x-www-form-urlencoded->表单数据
     79             connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
     80 
     81             // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
     82             connection.connect();
     83 
     84             // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
     85             DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
     86             String parm = "storeId=" + URLEncoder.encode("32", "utf-8"); // URLEncoder.encode()方法 为字符串进行编码
     87 
     88             // 将参数输出到连接
     89             dataout.writeBytes(parm);
     90 
     91             // 输出完成后刷新并关闭流
     92             dataout.flush();
     93             dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)
     94 
     95             System.out.println(connection.getResponseCode());
     96 
     97             // 连接发起请求,处理服务器响应 (从连接获取到输入流并包装为bufferedReader)
     98             BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
     99             @SuppressWarnings("unused")
    100             String line = null;
    101             StringBuilder sb = new StringBuilder(); // 用来存储响应数据
    102 
    103             // 循环读取流,若不到结尾处
    104             while ((line = bf.readLine()) != null) {
    105                 sb.append(bf.readLine());
    106             }
    107             bf.close(); // 重要且易忽略步骤 (关闭流,切记!)
    108             connection.disconnect(); // 销毁连接
    109             System.out.println(sb.toString());
    110 
    111         } catch (Exception e) {
    112             e.printStackTrace();
    113         }
    114     }
    115 
    116     /**
    117      * get 请求 @param @param url @return String @throws
    118      */
    119     public static String doGetStr(String url) {
    120         DefaultHttpClient httpClient = new DefaultHttpClient();
    121         HttpGet httpGet = new HttpGet(url);
    122         String result = "";
    123 
    124         try {
    125             HttpResponse response = httpClient.execute(httpGet);
    126             HttpEntity entity = response.getEntity();
    127             if (entity != null) {
    128                 result = EntityUtils.toString(entity, "UTF-8");
    129             }
    130         } catch (ClientProtocolException e) {
    131             e.printStackTrace();
    132         } catch (IOException e) {
    133             e.printStackTrace();
    134         } finally {
    135             HttpClientUtils.closeQuietly(httpClient);
    136         }
    137         return result;
    138     }
    139 
    140     /**
    141      * post 请求 @param @param url @param @param outStr @throws
    142      */
    143     public static String doPostStr(String url, String outStr) {
    144         DefaultHttpClient httpClient = new DefaultHttpClient();
    145         HttpPost httpPost = new HttpPost();
    146         String result = "";
    147 
    148         try {
    149             httpPost.setEntity(new StringEntity(outStr, "UTF-8"));
    150             HttpResponse response = httpClient.execute(httpPost);
    151             result = EntityUtils.toString(response.getEntity(), "UTF-8");
    152         } catch (ClientProtocolException e) {
    153             e.printStackTrace();
    154         } catch (IOException e) {
    155             e.printStackTrace();
    156         } finally {
    157             HttpClientUtils.closeQuietly(httpClient);
    158         }
    159         return result;
    160     }
    161 }

    以上是个人根据网上总结的几种请求方法。

  • 相关阅读:
    idea中svn代码冲突
    数据库表的连接(Left join , Right Join, Inner Join)用法详解
    @Param注解的用法解析
    spring @Transactional注解参数详解
    数据库的DDL、DML和DCL的区别与理解
    Mybatis:resultMap的使用总结
    Maps.newHashMap 和 new HashMap的区别
    php 个推的例子
    fidder 调接口 的 小常识
    php Memcached
  • 原文地址:https://www.cnblogs.com/lfyu/p/9257112.html
Copyright © 2011-2022 走看看