zoukankan      html  css  js  c++  java
  • Java模拟http请求调用远程接口工具类

      1 package ln;
      2 
      3 import java.io.BufferedReader;
      4 import java.io.IOException;
      5 import java.io.InputStreamReader;
      6 import java.io.PrintWriter;
      7 import java.util.HashMap;
      8 import java.util.List;
      9 import java.util.Map;
     10 
     11 /**
     12  * 用于模拟HTTP请求中GET/POST方式 
     13  * @author landa
     14  *
     15  */
     16 public class HttpUtils {  
     17     /** 
     18      * 发送GET请求 
     19      *  
     20      * @param url 
     21      *            目的地址 
     22      * @param parameters 
     23      *            请求参数,Map类型。 
     24      * @return 远程响应结果 
     25      */  
     26     public static String sendGet(String url, Map<String, String> parameters) { 
     27         String result="";
     28         BufferedReader in = null;// 读取响应输入流  
     29         StringBuffer sb = new StringBuffer();// 存储参数  
     30         String params = "";// 编码之后的参数
     31         try {
     32             // 编码请求参数  
     33             if(parameters.size()==1){
     34                 for(String name:parameters.keySet()){
     35                     sb.append(name).append("=").append(
     36                             java.net.URLEncoder.encode(parameters.get(name),  
     37                             "UTF-8"));
     38                 }
     39                 params=sb.toString();
     40             }else{
     41                 for (String name : parameters.keySet()) {  
     42                     sb.append(name).append("=").append(  
     43                             java.net.URLEncoder.encode(parameters.get(name),  
     44                                     "UTF-8")).append("&");  
     45                 }  
     46                 String temp_params = sb.toString();  
     47                 params = temp_params.substring(0, temp_params.length() - 1);  
     48             }
     49             String full_url = url + "?" + params; 
     50             System.out.println(full_url); 
     51             // 创建URL对象  
     52             java.net.URL connURL = new java.net.URL(full_url);  
     53             // 打开URL连接  
     54             java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL  
     55                     .openConnection();  
     56             // 设置通用属性  
     57             httpConn.setRequestProperty("Accept", "*/*");  
     58             httpConn.setRequestProperty("Connection", "Keep-Alive");  
     59             httpConn.setRequestProperty("User-Agent",  
     60                     "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");  
     61             // 建立实际的连接  
     62             httpConn.connect();  
     63             // 响应头部获取  
     64             Map<String, List<String>> headers = httpConn.getHeaderFields();  
     65             // 遍历所有的响应头字段  
     66             for (String key : headers.keySet()) {  
     67                 System.out.println(key + "	:	" + headers.get(key));  
     68             }  
     69             // 定义BufferedReader输入流来读取URL的响应,并设置编码方式  
     70             in = new BufferedReader(new InputStreamReader(httpConn  
     71                     .getInputStream(), "UTF-8"));  
     72             String line;  
     73             // 读取返回的内容  
     74             while ((line = in.readLine()) != null) {  
     75                 result += line;  
     76             }  
     77         } catch (Exception e) {
     78             e.printStackTrace();
     79         }finally{
     80             try {  
     81                 if (in != null) {  
     82                     in.close();  
     83                 }  
     84             } catch (IOException ex) {  
     85                 ex.printStackTrace();  
     86             }  
     87         }
     88         return result ;
     89     }  
     90   
     91     /** 
     92      * 发送POST请求 
     93      *  
     94      * @param url 
     95      *            目的地址 
     96      * @param parameters 
     97      *            请求参数,Map类型。 
     98      * @return 远程响应结果 
     99      */  
    100     public static String sendPost(String url, Map<String, String> parameters) {  
    101         String result = "";// 返回的结果  
    102         BufferedReader in = null;// 读取响应输入流  
    103         PrintWriter out = null;  
    104         StringBuffer sb = new StringBuffer();// 处理请求参数  
    105         String params = "";// 编码之后的参数  
    106         try {  
    107             // 编码请求参数  
    108             if (parameters.size() == 1) {  
    109                 for (String name : parameters.keySet()) {  
    110                     sb.append(name).append("=").append(  
    111                             java.net.URLEncoder.encode(parameters.get(name),  
    112                                     "UTF-8"));  
    113                 }  
    114                 params = sb.toString();  
    115             } else {  
    116                 for (String name : parameters.keySet()) {  
    117                     sb.append(name).append("=").append(  
    118                             java.net.URLEncoder.encode(parameters.get(name),  
    119                                     "UTF-8")).append("&");  
    120                 }  
    121                 String temp_params = sb.toString();  
    122                 params = temp_params.substring(0, temp_params.length() - 1);  
    123             }  
    124             // 创建URL对象  
    125             java.net.URL connURL = new java.net.URL(url);  
    126             // 打开URL连接  
    127             java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL  
    128                     .openConnection();  
    129             // 设置通用属性  
    130             httpConn.setRequestProperty("Accept", "*/*");  
    131             httpConn.setRequestProperty("Connection", "Keep-Alive");  
    132             httpConn.setRequestProperty("User-Agent",  
    133                     "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");  
    134             // 设置POST方式  
    135             httpConn.setDoInput(true);  
    136             httpConn.setDoOutput(true);  
    137             // 获取HttpURLConnection对象对应的输出流  
    138             out = new PrintWriter(httpConn.getOutputStream());  
    139             // 发送请求参数  
    140             out.write(params);  
    141             // flush输出流的缓冲  
    142             out.flush();  
    143             // 定义BufferedReader输入流来读取URL的响应,设置编码方式  
    144             in = new BufferedReader(new InputStreamReader(httpConn  
    145                     .getInputStream(), "UTF-8"));  
    146             String line;  
    147             // 读取返回的内容  
    148             while ((line = in.readLine()) != null) {  
    149                 result += line;  
    150             }  
    151         } catch (Exception e) {  
    152             e.printStackTrace();  
    153         } finally {  
    154             try {  
    155                 if (out != null) {  
    156                     out.close();  
    157                 }  
    158                 if (in != null) {  
    159                     in.close();  
    160                 }  
    161             } catch (IOException ex) {  
    162                 ex.printStackTrace();  
    163             }  
    164         }  
    165         return result;  
    166     }  
    167   
    168     /** 
    169      * 主函数,测试请求 
    170      *  
    171      * @param args 
    172      */  
    173     public static void main(String[] args) {  
    174         Map<String, String> parameters = new HashMap<String, String>();  
    175         parameters.put("name", "sarin");  
    176         String result =sendGet("http://www.baidu.com", parameters);
    177         System.out.println(result); 
    178     }  
    179 }
  • 相关阅读:
    多线程与Socket编程
    正则表达式
    委托事件泛型
    C#基础加强
    随笔
    不设置JAVA_HOME运行eclipse
    CentOS7.x系统中使用Docker时,在存储方面需要注意的问题
    【转】关于高可用负载均衡的探索-基于Rancher和Traefic
    Rancher 容器管理平台-免费视频培训-链接及内容-第三季
    使用Rancher的RKE快速部署Kubernetes集群
  • 原文地址:https://www.cnblogs.com/bigbrid/p/6656725.html
Copyright © 2011-2022 走看看