因为经常用到 便写出来方边使用 直接复制本类即可

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * 封装HttpURLConnection开箱即用
 * Create by yster@foxmail.com 2018/9/10/010 19:17
 */
public class HttpUtil {
    private HttpURLConnection connection;
    private Charset charset = Charset.forName("UTF-8");
    private int readTimeout = 32000;
    private int connectTimeout = 10000;
    private String method = "GET";
    private boolean doInput = true;
    private Map<String, String> headers = null;
    private String data = null;

    /**
     * 实例化对象
     */
    public static HttpUtil connect(String url) throws IOException {
        return new HttpUtil((HttpURLConnection) new URL(url).openConnection());
    }

    /**
     * 禁止new实例
     */
    private HttpUtil() {
    }

    private HttpUtil(HttpURLConnection connection) {
        this.connection = connection;
    }

    /**
     * 设置读去超时时间/ms
     *
     * @param timeout
     */
    public HttpUtil setReadTimeout(int timeout) {
        this.readTimeout = timeout;
        return this;
    }

    /**
     * 设置链接超时时间/ms
     *
     * @param timeout
     */
    public HttpUtil setConnectTimeout(int timeout) {
        this.connectTimeout = timeout;
        return this;
    }

    /**
     * 设置请求方式
     *
     * @param method
     */
    public HttpUtil setMethod(String method) {
        this.method = method;
        return this;
    }

    /**
     * 添加Headers
     *
     * @param map
     */
    public HttpUtil setHeaders(Map<String, String> map) {
        String cookie = "Cookie";
        if (map.containsKey(cookie)) {
            headers = new HashMap<>();
            headers.put(cookie, map.get(cookie));
        }
        return this;
    }

    /**
     * 是否接受输入流
     * 默认true
     *
     * @param is
     */
    public HttpUtil setDoInput(boolean is) {
        this.doInput = is;
        return this;
    }

    /**
     * 设置请求响应的编码
     */
    public HttpUtil setCharset(String charset) {
        this.charset = Charset.forName(charset);
        return this;
    }

    /**
     * 写入数据,接受Map<String,String>或String类型<br>
     * 例如POST时的参数<br>
     * demo=1&name=2
     */
    public HttpUtil setData(Object object) {
        if (object == null) {
            return this;
        } else if (object instanceof String) {
            this.data = (String) object;
        } else if (object instanceof Map) {
            Map map = (Map) object;
            StringBuilder builder = new StringBuilder();
            for (Object key : map.keySet()) {
                builder.append(key + "=" + map.get(key) + "&");
            }
            this.data = builder.toString().substring(0, builder.length() > 0 ? builder.length() - 1 : builder.length());
        }
        return this;
    }

    /**
     * 发起请求
     */
    public HttpUtil execute() throws IOException {
        //添加请求头
        if (headers != null) {
            for (String key : headers.keySet()) {
                connection.setRequestProperty(key, headers.get(key));
            }
        }
        //设置读去超时时间为10秒
        connection.setReadTimeout(readTimeout);
        //设置链接超时为10秒
        connection.setConnectTimeout(connectTimeout);
        //设置请求方式,GET,POST
        connection.setRequestMethod(method.toUpperCase());
        //接受输入流
        connection.setDoInput(doInput);
        //写入参数
        if (data != null && !method.equalsIgnoreCase("GET")) {
            //启动输出流,当需要传递参数时需要开启
            connection.setDoOutput(true);
            //添加请求参数,注意:如果是GET请求,参数要写在URL中
            OutputStream output = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, charset));
            //写入参数 用&分割。
            writer.write(data);
            writer.flush();
            writer.close();
        }
        //发起请求
        connection.connect();
        return this;
    }

    /**
     * 获取HttpURLConnection
     */
    public HttpURLConnection getConnection() {
        return this.connection;
    }

    /**
     * 获取响应字符串
     */
    public String getBody(String... charsets) {
     //设置编码
        String charset = "UTF-8";
        if (charsets.length > 0) {
            charset = charsets[0];
        }
     //读取输入流
        try {
            InputStream inputStream = connection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, charset));
            String line = bufferedReader.readLine();
            StringBuilder builder = new StringBuilder();
            while (line != null) {
                builder.append(line);
                line = bufferedReader.readLine();
            }
            return builder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
     //失败返回NULL
        return null;
    }

    public static void main(String[] args) throws IOException {
        String body = HttpUtil.connect("http://www.baidu.com")
                .setMethod("GET")
                .setCharset("UTF-8")
                .execute()
                .getBody();
        System.out.println(body);
    }

}

  

封装HttpUrlConnection开箱即用的更多相关文章

  1. 封装HttpURLConnection

    package com.pingyijinren.test; import java.io.BufferedReader; import java.io.InputStream; import jav ...

  2. J1001.Java原生桌面及Web开发浅谈

    自从Java问世以来,在服务端开发方面取得了巨大的发展.但是在桌面/Web开发方面,一直没有得到大的发展.从最初的AWT,到Swing,再到JavaFX,Java从来没有在桌面/Web解决方案中取得重 ...

  3. Android:Volley源代码解析

    简单实例 Volley是一个封装HttpUrlConnection和HttpClient的网络通信框架,集AsyncHttpClient和Universal-Image-Loader的长处于了一身.既 ...

  4. $《第一行代码:Android》读书笔记——第10章 Android网络编程

    (一)WebView的用法 1.WebView也是一个普通的控件. 2.常用用法: WebView webView = (WebView)findViewById(R.id.web_view); we ...

  5. Volley框架源代码分析

    Volley框架分析Github链接 Volley框架分析 Volley源代码解析 为了学习Volley的网络框架,我在AS中将Volley代码又一次撸了一遍,感觉这样的照抄代码也是一种挺好的学习方式 ...

  6. Gong服务实现平滑重启分析

    平滑重启是指能让我们的程序在重启的过程不中断服务,新老进程无缝衔接,实现零停机时间(Zero-Downtime)部署: 平滑重启是建立在优雅退出的基础之上的,之前一篇文章介绍了相关实现:Golang中 ...

  7. Spring Cloud 系列之 Netflix Zuul 服务网关

    什么是 Zuul Zuul 是从设备和网站到应用程序后端的所有请求的前门.作为边缘服务应用程序,Zuul 旨在实现动态路由,监视,弹性和安全性.Zuul 包含了对请求的路由和过滤两个最主要的功能. Z ...

  8. Spring Cloud 系列之 Gateway 服务网关(一)

    什么是 Spring Cloud Gateway Spring Cloud Gateway 作为 Spring Cloud 生态系统中的网关,目标是替代 Netflix Zuul,其不仅提供统一的路由 ...

  9. Vue+EasyPOI导出Excel(带图片)

    一.前言 平时的工作中,Excel 导入导出功能是非常常见的功能,无论是前端 Vue (js-xlsx) 还是 后端 Java (POI),如果让大家手动编码实现的话,恐怕就很麻烦了,尤其是一些定制化 ...

随机推荐

  1. Oracle 表锁与解锁

    1. 查询 Oralce 被锁定的表信息 select object_name,machine,s.sid,s.serial#from v$locked_object l,dba_objects o ...

  2. python LeetCode 两数相除

    近一个月一直在写业务,空闲时间刷刷leetcode,刷题过程中遇到了一道比较有意思的题目,和大家分享. 题目描述: 给定两个整数,被除数 dividend 和除数 divisor.将两数相除,要求不使 ...

  3. LeetCode题解之Squares of a Sorted Array

    1.题目描述 2.问题分析 使用过两个计数器. 3.代码 class Solution { public: vector<int> sortedSquares(vector<int& ...

  4. 线程ThreadDemo04

    package day190109; public class 线程ThreadDemo04 { public static void main(String[] args) throws Inter ...

  5. Docker: dockerfile常用关键字

    Dockerfile指令 Dockfile执行和shell命令一行,一行一行执行- 写Dockerfile注意点: 1.           尽量少RUN 2.           多个命令拼接在一起 ...

  6. win21api、win32gui、win32con三个模块操作系统窗口时一些小技巧

    下面这段脚本是操作一个浏览器上弹窗,打开文件窗口,由于脚本 执行速度快,当时未添加第2行的延时时,脚本顺利的执行成功,但弹的窗却没有进行操作,建议后续如果脚本执行到打开弹窗时,延时个几秒再去操作所弹窗 ...

  7. ORM版学员管理系统2

    学生信息管理 展示学生信息 URL部分 url(r'^student_list/', app01_views.student_list, name="student_list"), ...

  8. 【Teradata】磁盘碎片整理(ferret工具)

    DEFRAGMENTcombines free sectors and moves them to the end of a cylinder.PACKDISKfill (or packs) cyli ...

  9. 【C编程基础】C程序常用函数

    基础知识 1.const const 修饰的数据类型是指常类型,常类型的变量或对象的值是不能被更新的. ; 或 ; //在定义该const变量时,通常需要对它进行初始化,因为以后就没有机会再改变它了 ...

  10. 【Linux基础】VI命令模式下大小写转换

    [开始位置] ---- 可以指定开始的位置,默认是光标的当前位置 gu ---- 把选择范围全部小写 gU ---- 把选择范围全部大写 [结束位置] ---- 可以跟着类似的w,6G,gg等定位到错 ...