封装HttpUrlConnection开箱即用
因为经常用到 便写出来方边使用 直接复制本类即可
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开箱即用的更多相关文章
- 封装HttpURLConnection
package com.pingyijinren.test; import java.io.BufferedReader; import java.io.InputStream; import jav ...
- J1001.Java原生桌面及Web开发浅谈
自从Java问世以来,在服务端开发方面取得了巨大的发展.但是在桌面/Web开发方面,一直没有得到大的发展.从最初的AWT,到Swing,再到JavaFX,Java从来没有在桌面/Web解决方案中取得重 ...
- Android:Volley源代码解析
简单实例 Volley是一个封装HttpUrlConnection和HttpClient的网络通信框架,集AsyncHttpClient和Universal-Image-Loader的长处于了一身.既 ...
- $《第一行代码:Android》读书笔记——第10章 Android网络编程
(一)WebView的用法 1.WebView也是一个普通的控件. 2.常用用法: WebView webView = (WebView)findViewById(R.id.web_view); we ...
- Volley框架源代码分析
Volley框架分析Github链接 Volley框架分析 Volley源代码解析 为了学习Volley的网络框架,我在AS中将Volley代码又一次撸了一遍,感觉这样的照抄代码也是一种挺好的学习方式 ...
- Gong服务实现平滑重启分析
平滑重启是指能让我们的程序在重启的过程不中断服务,新老进程无缝衔接,实现零停机时间(Zero-Downtime)部署: 平滑重启是建立在优雅退出的基础之上的,之前一篇文章介绍了相关实现:Golang中 ...
- Spring Cloud 系列之 Netflix Zuul 服务网关
什么是 Zuul Zuul 是从设备和网站到应用程序后端的所有请求的前门.作为边缘服务应用程序,Zuul 旨在实现动态路由,监视,弹性和安全性.Zuul 包含了对请求的路由和过滤两个最主要的功能. Z ...
- Spring Cloud 系列之 Gateway 服务网关(一)
什么是 Spring Cloud Gateway Spring Cloud Gateway 作为 Spring Cloud 生态系统中的网关,目标是替代 Netflix Zuul,其不仅提供统一的路由 ...
- Vue+EasyPOI导出Excel(带图片)
一.前言 平时的工作中,Excel 导入导出功能是非常常见的功能,无论是前端 Vue (js-xlsx) 还是 后端 Java (POI),如果让大家手动编码实现的话,恐怕就很麻烦了,尤其是一些定制化 ...
随机推荐
- 【最新】Android使用jenkins全自动构建打包-Windows版本(Android,Jenkins,360加固,Email,QRcode,参数构建,蒲公英)
Android打包喝咖啡系列(Windows版) 这篇博客主要讲述的内容: 1.windows上部署Jenkins https://jenkins.io 2.基于SVN或Git https://git ...
- (网页)swiper.js轮播图插件
Swiper4.x使用方法 1.首先加载插件,需要用到的文件有swiper.min.js和swiper.min.css文件.可下载Swiper文件或使用CDN. <!DOCTYPE html&g ...
- matlab练习程序(加权最小二乘)
起本篇题目还是比较纠结的,原因是我本意打算寻找这样一个算法:在测量数据有比较大离群点时如何估计原始模型. 上一篇曲面拟合是假设测量数据基本符合均匀分布,没有特别大的离群点的情况下,我们使用最小二乘得到 ...
- Linux CentOS7下安装Python3及其setuptools、pip
CentOS 7系统自带Python2.7,我们尽量别去卸载它!!否则会出问题,比如yum无法使用等问题. 假若,在安装Python3时没有自动安装setuptools和pip,那么,如何在CentO ...
- c/c++ 智能指针 unique_ptr 使用
智能指针 unique_ptr 使用 和shared_ptr不同,可以有多个shared_ptr指向同一个内存,只能有1个unique_ptr指向某个内存.因此unique_ptr不支持普通的拷贝和赋 ...
- Win10 - MySQL-zip安装方法
Win10 - MySQL-zip安装方法 安装步骤 1.下载,到MySQL官网:https://dev.mysql.com/downloads/mysql/ 2.解压安装包 解压下载的安装包,放到你 ...
- February 26th, 2018 Week 9th Monday
A good beginning is half done. 良好的开端是成功的一半. We can't finish anything if we don't start, sometimes ge ...
- Spring容器技术内幕之BeanWrapper类介绍
引言 org.springframework.beans.BeanWrapper是Spring框架中重要的组件类.BeanWrapper相当于一个代理器,Spring委托BeanWrapperwanc ...
- PostgreSQL条件表达式 case when then end
例: SELECT CASE WHEN (store_size <= (100)::NUMERIC) THEN '小店'::TEXT WHEN (store_size >= (200):: ...
- 关于图片的Base64编码
什么是Base64编码 Base64编码是一种图片处理格式,通过特定的算法将图片编码成一长串字符串,在页面上显示的时候,可以用该字符串来代替图片的url属性. base64编码就是长得像下面这样子的代 ...