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

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. Git:二、本地文件操作

    文件必须放在本地Git仓库的文件夹下,子文件夹也可以. 1.添加/修改 git add <文件名> 2.提交 git commit -m "本次提交说明" 可以add很 ...

  2. ubuntu 安装PG10 更新packet 创建超级账号

    ubuntu 安装PG10 更新packet 创建超级账号 安装pg10 我的环境是16.04 server版本 MAC和windows 建议使用安装包 直接官网下载 echo 'deb http:/ ...

  3. SQL Server Replication的分发服务器的快照文件夹位置查找

    SQL Server分发服务器配置中,需要配置快照文件夹(Snapshot Folder),用于存储发布的数据和架构文件的工作目录,那么如何查找当前SQL Server数据库服务器的分发服务器的快照文 ...

  4. Javascript 高级程序设计--总结【四】

    *******************************  Chapter 11 DOM扩展  ******************************* 主要的扩展是 选择符API 和 H ...

  5. SQL server 获得 表的主键,自增键

    主键: @tableName --表名 @id ---表对应的id SELECT SYSCOLUMNS.name FROM SYSCOLUMNS,SYSOBJECTS,SYSINDEXES,SYSIN ...

  6. NPOI导入导出Excel工具类

    using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Ref ...

  7. Hibernate 5 入门指南-基于Envers

    首先创建\META-INF\persistence.xml配置文件并做简单的配置 <persistence xmlns="http://java.sun.com/xml/ns/pers ...

  8. C语言 统计一串字符中空格键、Tab键、回车键、字母、数字及其他字符的个数(Ctrl+Z终止输入)

    //凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/ #include<stdio.h> void main(){ , num=, blank=, ...

  9. background-image使用svg如何改变颜色

    结论 在我多番测试之后,才发现background-image使用svg,改变颜色根本做不了. 分析 当svg图片被使用成background-image,颜色的设置需要在svg内部才能生效.在外部C ...

  10. 【C编程基础】多线程编程

    基础知识 1.基本概念 (1)线程,即轻量级进程(LWP:LightWeight Process),是程序执行流的最小单元. 线程是进程中的一个实体,是被系统独立调度和分派的基本单位. (2)线程同步 ...