封装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 ...
- Anaconda管理Python环境
Anaconda介绍 Anaconda指的是一个开源的Python发行版本,其包含了conda.Python等180多个科学包及其依赖项.Anaconda提供环境管理的功能,功能类似 Virtuale ...
- 【软件需求工程与建模 - 小组项目】第6周 - 成果展示3 - 软件设计规格说明书V4.1
成果展示3 - 软件设计规格说明书V4.1
- Eclipse引入spring约束详细教程
1.打开eclipse的window-preferences,搜索catalog. 2.点击add,点击File System,弹出页面选择spring-beans-4.2.xsd. 3.key ty ...
- web前端(14)—— JavaScript的数据类型,语法规范1
编辑器选择 对js的编辑器选用,有很多,能对html编辑的,也能对js编辑,比如notepad++,visual studio code,webstom,atom,pycharm,sublime te ...
- c/c++ 数组的智能指针 使用
数组的智能指针 使用 数组的智能指针的限制: 1,unique_ptr的数组智能指针,没有*和->操作,但支持下标操作[] 2,shared_ptr的数组智能指针,有*和->操作,但不支持 ...
- 7. svg学习笔记-图案和渐变
之前,我们仅仅使用纯色来为图形填充颜色和绘制轮廓,除此之外,我们还可以使用图案和渐变来填充图形或者是绘制轮廓. 图案 图案的效果类似于,在网页中给一个元素指定背景图像,当背景图像的尺寸小于元素的尺寸的 ...
- python多线程与多进程--存活主机ping扫描以及爬取股票价格
python多线程与多进程 多线程: 案例:扫描给定网络中存活的主机(通过ping来测试,有响应则说明主机存活) 普通版本: #扫描给定网络中存活的主机(通过ping来测试,有响应则说明主机存活)im ...
- Selenium Webdriver 中的 executeScript 使用方法
1.使用executeScript 返回一个WebElement . 下例中我们将一个浏览器中的JavaScript 对象返回到客户端(C#,JAVA,Python等). IWebElement el ...
- ctf学习(web题二)
web 下面是做bugku上一些web的总结 内容链接