封装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」adb调试源码(针对dumpsys SurfceFlinger、trace.txt获取)
首先对ADB作简单的阐述,接下来对adb shell dumpsys SurfaceFlinger服务的dump信息的查看.以及ANR问题如何获取trace文件并简单分析. -×*********** ...
- 解决tomcat中文传输乱码问题
<Connector URIEncoding="utf-8" connectionTimeout="20000" encoding="utf-8 ...
- C#发布和调试WebService
一.编写并发布WebService服务 1.新建空web应用程序
- c/c++ 标准库 map set 插入
标准库 map set 插入 一,插入操作 有map如下: map<string, size_t> cnt; 插入方法: 插入操作种类 功能描述 cnt.insert({"abc ...
- Python的变量以及类型
1.程序是用来处理数据的,变量就是用来存储数据的 num1 = 100 2.为了更充分的利用内存空间以及更有效率的管理内存,变量是有不同的类型 3.怎样知道一个变量的类型呢? 3.1 在python ...
- 快速启动神器 Wox
wox(快速启动程序) wox官网:http://www.wox.one/ 下载wox:https://github.com/Wox-launcher/Wox/releases wox插件库:http ...
- Sublime Text 2 配置PHP调试环境(在windows环境下)
1:PHP安装,配置环境变量 PHP安装略过- 2:下载Sublime Text 2 下载地址:http://www.sublimetext.com/2 ,选择自己合适的版本 3:点击 sublime ...
- 如何解决make时报错crti. o: unrecognized relocation (0x2a) in section `.init
这个问题困扰了我好长时间,网上查了好长时间,这个问题的解决方法,就是将binultils升级到2.26. 造成这个问题的原因是gcc和binultils版本不匹配,gcc对应的版本较高,gcc编译后, ...
- ionic app开发遇到的问题
:processDebugResources FAILED FAILURE: Build failed with an exception. * What went wrong: Execution ...
- C#基础知识之List和数组之间的转换
1,从System.String[]转到List<System.String> System.String[] str={"str","string" ...