• 【Java】+http


    声明:知识来源于 https://www.jb51.net/article/160395.htm

    1、前言:

    2、常用的2种方式

    1、一种是通过HTTPClient这种第三方的开源框架去实现

    2、一种是通过HttpURLConnection去实现,HttpURLConnection是JAVA的标准类,是JAVA比较原生的一种实现方式。(个人推荐)


    2.1、方式1 HTTPClient:

    package com.powerX.httpClient;
    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    public class HttpClient4 {
    
    /** 请求方式1 : GET*/
      public static String doGet(String url) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
          // 通过址默认配置创建一个httpClient实例
          httpClient = HttpClients.createDefault();
          // 创建httpGet远程连接实例
          HttpGet httpGet = new HttpGet(url);
          // 设置请求头信息,鉴权
          httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
          // 设置配置请求参数
          RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
              .setConnectionRequestTimeout(35000)// 请求超时时间
              .setSocketTimeout(60000)// 数据读取超时时间
              .build();
          // 为httpGet实例设置配置
          httpGet.setConfig(requestConfig);
          // 执行get请求得到返回对象
          response = httpClient.execute(httpGet);
          // 通过返回对象获取返回数据
          HttpEntity entity = response.getEntity();
          // 通过EntityUtils中的toString方法将结果转换为字符串
          result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        } finally {
          // 关闭资源
          if (null != response) {
            try {
              response.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
          if (null != httpClient) {
            try {
              httpClient.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
        return result;
      }
    
    /** 请求方式2 : POST*/
      public static String doPost(String url, Map<String, Object> paramMap) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        // 创建httpClient实例
        httpClient = HttpClients.createDefault();
        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost(url);
        // 配置请求参数实例
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
            .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
            .setSocketTimeout(60000)// 设置读取数据连接超时时间
            .build();
        // 为httpPost实例设置配置
        httpPost.setConfig(requestConfig);
        // 设置请求头
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // 封装post请求参数
        if (null != paramMap && paramMap.size() > 0) {
          List<NameValuePair> nvps = new ArrayList<NameValuePair>();
          // 通过map集成entrySet方法获取entity
          Set<Entry<String, Object>> entrySet = paramMap.entrySet();
          // 循环遍历,获取迭代器
          Iterator<Entry<String, Object>> iterator = entrySet.iterator();
          while (iterator.hasNext()) {
            Entry<String, Object> mapEntry = iterator.next();
            nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
          }
    
          // 为httpPost设置封装好的请求参数
          try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
          } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
          }
        }
        try {
          // httpClient对象执行post请求,并返回响应参数对象
          httpResponse = httpClient.execute(httpPost);
          // 从响应对象中获取响应内容
          HttpEntity entity = httpResponse.getEntity();
          result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        } finally {
          // 关闭资源
          if (null != httpResponse) {
            try {
              httpResponse.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
          if (null != httpClient) {
            try {
              httpClient.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
        return result;
      }
    }

    2.2、方式2 HttpURLConnection:

    package com.powerX.httpClient;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    public class HttpClient {
    
    /** 请求方式1 : GET*/
      public static String doGet(String httpurl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
          // 创建远程url连接对象
          URL url = new URL(httpurl);
          // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
          connection = (HttpURLConnection) url.openConnection();
          // 设置连接方式:get
          connection.setRequestMethod("GET");
          // 设置连接主机服务器的超时时间:15000毫秒
          connection.setConnectTimeout(15000);
          // 设置读取远程返回的数据时间:60000毫秒
          connection.setReadTimeout(60000);
          // 发送请求
          connection.connect();
          // 通过connection连接,获取输入流
          if (connection.getResponseCode() == 200) {
            is = connection.getInputStream();
            // 封装输入流is,并指定字符集
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            // 存放数据
            StringBuffer sbf = new StringBuffer();
            String temp = null;
            while ((temp = br.readLine()) != null) {
              sbf.append(temp);
              sbf.append("
    ");
            }
            result = sbf.toString();
          }
        } catch (MalformedURLException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        } finally {
          // 关闭资源
          if (null != br) {
            try {
              br.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
    
          if (null != is) {
            try {
              is.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
    
          connection.disconnect();// 关闭远程连接
        }
    
        return result;
      }
    
    /** 请求方式12: POST*/
      public static String doPost(String httpUrl, String param) {
    
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
          URL url = new URL(httpUrl);
          // 通过远程url连接对象打开连接
          connection = (HttpURLConnection) url.openConnection();
          // 设置连接请求方式
          connection.setRequestMethod("POST");
          // 设置连接主机服务器超时时间:15000毫秒
          connection.setConnectTimeout(15000);
          // 设置读取主机服务器返回数据超时时间:60000毫秒
          connection.setReadTimeout(60000);
    
          // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
          connection.setDoOutput(true);
          // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
          connection.setDoInput(true);
          // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
          connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
          // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
          connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
          // 通过连接对象获取一个输出流
          os = connection.getOutputStream();
          // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
          os.write(param.getBytes());
          // 通过连接对象获取一个输入流,向远程读取
          if (connection.getResponseCode() == 200) {
    
            is = connection.getInputStream();
            // 对输入流对象进行包装:charset根据工作项目组的要求来设置
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    
            StringBuffer sbf = new StringBuffer();
            String temp = null;
            // 循环遍历一行一行读取数据
            while ((temp = br.readLine()) != null) {
              sbf.append(temp);
              sbf.append("
    ");
            }
            result = sbf.toString();
          }
        } catch (MalformedURLException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        } finally {
          // 关闭资源
          if (null != br) {
            try {
              br.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
          if (null != os) {
            try {
              os.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
          if (null != is) {
            try {
              is.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
          // 断开与远程地址url的连接
          connection.disconnect();
        }
        return result;
      }
    }

    3、封装后

    备注:可直接copy走使用

    maven依赖:

            <!--            http 请求         -->
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.3</version>
            </dependency>
            <!--        阿里巴巴处理JSON          -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.47</version>
            </dependency>

    代码:

    package com.http;
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    import com.alibaba.fastjson.serializer.SerializerFeature;
    
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.sql.SQLOutput;
    import java.util.Map;
    
    /**
     * @Author: Jarvis
     * @Date: 2020/5/12 15:56
     * @Version: v1.0.0
     * @Description: HttpURLConnection方式http请求(get、post)
     */
    
    public class JHttpUtil {
        private static final String[] requestTypes = {"GET", "POST"};
    
        // 返回JSONObject格式
        public static JSONObject doGetReturnJSONObject(String httpUrl) {
            return baseRequestToJsonObject(requestTypes[0], httpUrl, null, null);
        }
    
        public static JSONObject doGetReturnJSONObject(String httpUrl, JSONObject params) {
            return baseRequestToJsonObject(requestTypes[0], httpUrl, null, params);
        }
    
        public static JSONObject doGetReturnJSONObject(String httpUrl, JSONObject params, JSONObject header) {
            return baseRequestToJsonObject(requestTypes[0], httpUrl, params, header);
        }
    
        public static JSONObject doPostReturnJSONObject(String httpUrl, JSONObject params) {
            return baseRequestToJsonObject(requestTypes[1], httpUrl, null, params);
        }
    
        public static JSONObject doGPostReturnJSONObject(String httpUrl, JSONObject params, JSONObject header) {
            return baseRequestToJsonObject(requestTypes[1], httpUrl, header, params);
        }
    
        // 返回JSONArray格式
        public static JSONArray doGetReturnJSONArray(String httpUrl) {
            return baseRequestToJsonArray(requestTypes[0], httpUrl, null, null);
        }
    
        public static JSONArray doGetReturnJSONArray(String httpUrl, JSONObject params) {
            return baseRequestToJsonArray(requestTypes[0], httpUrl, null, params);
        }
    
        public static JSONArray doGetReturnJSONArray(String httpUrl, JSONObject params, JSONObject header) {
            return baseRequestToJsonArray(requestTypes[0], httpUrl, params, header);
        }
    
        public static JSONArray doPostReturnJSONArray(String httpUrl, JSONObject params) {
            return baseRequestToJsonArray(requestTypes[1], httpUrl, null, params);
        }
    
        public static JSONArray doPostReturnJSONArray(String httpUrl, JSONObject params, JSONObject header) {
            return baseRequestToJsonArray(requestTypes[1], httpUrl, header, params);
        }
    
        // 返回String格式
        public static String doGetReturnString(String httpUrl) {
            return baseRequestToString(requestTypes[0], httpUrl, null, null);
        }
    
        public static String doGetReturnString(String httpUrl, JSONObject params) {
            return baseRequestToString(requestTypes[0], httpUrl, null, params);
        }
    
        public static String doGetReturnString(String httpUrl, JSONObject params, JSONObject header) {
            return baseRequestToString(requestTypes[0], httpUrl, params, header);
        }
    
        public static String doPostReturnString(String httpUrl, JSONObject params) {
            return baseRequestToString(requestTypes[1], httpUrl, null, params);
        }
    
        public static String doPostReturnString(String httpUrl, JSONObject params, JSONObject header) {
            return baseRequestToString(requestTypes[1], httpUrl, header, params);
        }
    
        private static JSONObject baseRequestToJsonObject(String requestType, String httpUrl, JSONObject header, JSONObject params) {
            String result = baseRequest(requestType, httpUrl, header, params);
            if (!result.startsWith("[{")) {
                return JSONObject.parseObject(result);
            }
            return null;
        }
    
        private static JSONArray baseRequestToJsonArray(String requestType, String httpUrl, JSONObject header, JSONObject params) {
            String result = baseRequest(requestType, httpUrl, header, params);
            if (result.startsWith("[{")) {
                return JSONArray.parseArray(result);
            }
            return null;
        }
    
        private static String baseRequestToString(String requestType, String httpUrl, JSONObject header, JSONObject params) {
            return baseRequest(requestType, httpUrl, header, params);
        }
    
        /**
         * 功能:请求配置基本方法
         *
         * @param requestType 请求类型(GET、POST 等等)
         * @param httpUrl     请求地址(纯地址 不带参数)
         * @param header      请求头(JSON格式)
         * @param params      请求参数(JSON格式)
         * @return 返回请求后的数据(JSON格式)
         */
        private static String baseRequest(String requestType, String httpUrl, JSONObject header, JSONObject params) {
            HttpURLConnection connection = null;
            InputStream is = null;
            OutputStream os = null;
            BufferedReader br = null;
            String result = null;// 返回结果字符串
            long startTime = 0;
            long endTime = 0;
            long gapTime = 0;
    
            // GET请求 参数配置(参数拼接到url)
            if (params != null && requestType == requestTypes[0]) {
                httpUrl += "?";
                int i = 0;
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    httpUrl += entry.getKey() + "=" + entry.getValue();
                    // 若不是最后一个参数 则加“&”
                    if (i < params.size() - 1) {
                        httpUrl += "&";
                    }
                    i++;
                }
            }
    
            try {
                // 创建远程url连接对象
                URL url = new URL(httpUrl);
                // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
                connection = (HttpURLConnection) url.openConnection();
    
                // 设置请求头
                if (header != null) {
                    for (Map.Entry<String, Object> entry : header.entrySet()) {
                        connection.setRequestProperty(entry.getKey(), String.valueOf(entry.getValue()));
                    }
                }
                connection.setRequestMethod(requestType); // 设置连接方式
                connection.setConnectTimeout(5 * 60 * 1000); // 设置连接主机服务器的超时时间:5分钟
                connection.setReadTimeout(5 * 60 * 1000); // 设置读取远程返回的数据时间:5分钟
    
                // 为POST请求时 打开输出流 并把参数传输出去
                if (requestType == requestTypes[1]) {
                    connection.setDoOutput(true);
                    // 通过连接对象获取一个输出流
                    os = connection.getOutputStream();
                    // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
                    os.write(params.toString().getBytes());
                }
    
                startTime = System.currentTimeMillis();
                connection.connect(); // 发送请求
    
                // 通过connection连接 获取输入流
                if (200 == connection.getResponseCode()) {
                    is = connection.getInputStream();
                    // 封装输入流is,并指定字符集
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    // 存放数据
                    StringBuffer sbf = new StringBuffer();
                    String temp = null;
                    while ((temp = br.readLine()) != null) {
                        sbf.append(temp);
                        sbf.append("
    ");
                    }
                    result = sbf.toString();
                }
                endTime = System.currentTimeMillis();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭资源
                if (null != br) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                connection.disconnect();// 关闭远程连接
            }
            gapTime = endTime - startTime;
            String resultJson = result;
    
            // 做个开关 是否打印请求及响应信息(供扩展)
            boolean isPrintRequestAndResponseData = true;
            if (isPrintRequestAndResponseData) {
                // 打印请求头
                System.out.println("******************** 请求响应数据 **********************");
                System.out.println(String.format("【请求耗时】:
    %sms", gapTime));
                System.out.println(String.format("【请求头】:
    %s", header));
                // 打印请求地址
                System.out.println(String.format("【请求地址】(%s):
    %s", requestType, httpUrl));
                // 打印请求数据(非GET)
                if (!requestType.equals(requestTypes[0])) {
                    System.out.println(String.format("【请求参数】:
    %s", JSON.toJSONString(
                            params,
                            SerializerFeature.PrettyFormat,
                            SerializerFeature.WriteMapNullValue,
                            SerializerFeature.WriteDateUseDateFormat)));
                }
                // 打印响应数据(若返回数据长度大于10000 则截取前50后50)
                // 做个开关 是否截取(供以后扩展)
                boolean isCutResponse = true;
                if (isCutResponse && resultJson.length() >= 10000) {
                    String frist = resultJson.substring(0, 50);
                    String last = resultJson.substring(resultJson.length() - 50, resultJson.length());
                    System.out.println(String.format("【返回数据】:
    %s", frist + "......返回数据长度大于10000 仅显示前50后50位......" + last));
                } else {
                    System.out.println(String.format("【返回数据】:
    %s", JSON.toJSONString(
                            resultJson,
                            SerializerFeature.PrettyFormat,
                            SerializerFeature.WriteMapNullValue,
                            SerializerFeature.WriteDateUseDateFormat)));
                }
                System.out.println("*******************************************************
    ");
            }
    
            return resultJson;
        }
    }
  • 相关阅读:
    指针问题,p+i什么意思i代表什么
    怎么用C语言写一个飞机程序
    switch()语句中()中必须是常量吗
    一元二次方程运行结果中输入上系数后总显示输入不合法无论系数可以得出实根
    我想学号图论求大神请教
    c-freelib库
    十进制转十六进制问题(有代码)
    关于逐个读取同一目录下txt文本的问题
    JAVA-JDK1.7-ConCurrentHashMap-测试和验证
    JAVA-JDK1.7-ConCurrentHashMap-源码并且debug说明
  • 原文地址:https://www.cnblogs.com/danhuai/p/11073325.html
Copyright © 2020-2023  润新知