HttpURLConnection访问url的工具类
直接贴代码:
import java.io.IOException;
import java.util.HashMap;
import java.util.Map; import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; /**
* HttpClientUtil
*/
public class HttpClientUtil { // 连接主机超时(30s)
public static final int HTTP_CONNECT_TIMEOUT_30S = 30 * 1000; // 从主机读取数据超时(3min)
public static final int HTTP_READ_TIMEOUT_3MIN = 180 * 1000; /**
* httpPost
*/
public static String httpPost(String url, String jsonParam) throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url); // 设置请求头和请求参数
if (null != jsonParam && !jsonParam.isEmpty()) {
StringEntity entity = new StringEntity(jsonParam, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
} // 超时时间设置
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(HTTP_READ_TIMEOUT_3MIN)
.setConnectTimeout(HTTP_CONNECT_TIMEOUT_30S).build();
httpPost.setConfig(requestConfig); // 发送请求
CloseableHttpResponse response = httpclient.execute(httpPost); // 获取返回内容
try {
HttpEntity entity = response.getEntity();
String str = EntityUtils.toString(entity);
EntityUtils.consume(entity); // 此句关闭了流
return str;
} finally {
response.close();
}
} /**
* httpPost get Cookies
*/
public static Map<String, Object> httpPostGetCookies(String url, String jsonParam) throws ClientProtocolException,
IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url); // 设置请求头和请求参数
if (null != jsonParam && !jsonParam.isEmpty()) {
StringEntity entity = new StringEntity(jsonParam, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
} // 超时时间设置
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(HTTP_READ_TIMEOUT_3MIN)
.setConnectTimeout(HTTP_CONNECT_TIMEOUT_30S).build();
httpPost.setConfig(requestConfig); // 发送请求
CloseableHttpResponse response = httpclient.execute(httpPost); // 获取返回内容
try {
HttpEntity entity = response.getEntity();
String str = EntityUtils.toString(entity);
EntityUtils.consume(entity); // 此句关闭了流 // 获取数据内容
Map<String, Object> map = new HashMap<String, Object>();
map.put("result", str); // 获取返回到额Cookies
Header[] headers = response.getHeaders("Set-Cookie");
map.put("cookies", headers); return map;
} finally {
response.close();
}
} /**
* httpGet
*/
public static String httpGet(String url) throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url); // 超时时间设置
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(HTTP_READ_TIMEOUT_3MIN)
.setConnectTimeout(HTTP_CONNECT_TIMEOUT_30S).build();
httpGet.setConfig(requestConfig); // 发送请求
CloseableHttpResponse response = httpclient.execute(httpGet); // 获取返回内容
try {
HttpEntity entity = response.getEntity();
String strResult = EntityUtils.toString(entity);
return strResult;
} finally {
response.close();
}
} /**
* httpGet with Cookies
*/
public static String httpGetWithCookies(String url, Header[] headers) throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url); // 超时时间设置
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(HTTP_READ_TIMEOUT_3MIN)
.setConnectTimeout(HTTP_CONNECT_TIMEOUT_30S).build();
httpGet.setConfig(requestConfig); // 设置请求头
if (headers != null && headers.length > 0) {
httpGet.setHeaders(headers);
} // 发送请求
CloseableHttpResponse response = httpclient.execute(httpGet); // 获取返回内容
try {
HttpEntity entity = response.getEntity();
String strResult = EntityUtils.toString(entity);
return strResult;
} finally {
response.close();
}
} }
HttpURLConnection访问url的工具类的更多相关文章
- 使用HttpClient访问url的工具类
maven依赖jar包配置: <dependency> <groupId>org.apache.httpcomponents</groupId> <artif ...
- 一、JDBC的概述 二、通过JDBC实现对数据的CRUD操作 三、封装JDBC访问数据的工具类 四、通过JDBC实现登陆和注册 五、防止SQL注入
一.JDBC的概述###<1>概念 JDBC:java database connection ,java数据库连接技术 是java内部提供的一套操作数据库的接口(面向接口编程),实现对数 ...
- UrlUtils工具类,Java URL工具类,Java URL链接工具类
UrlUtils工具类,Java URL工具类,Java URL链接工具类 >>>>>>>>>>>>>>>&g ...
- java服务器访问其他服务器工具类编写
java服务器访问其他服务器工具类编写适合各种消息推送及微服务交互 package com.xiruo.medbid.components; import com.xiruo.medbid.util. ...
- 从零开始学android开发-通过WebService进行网络编程,使用工具类轻松实现
相信大家在平常的开发中,对网络的操作用到HTTP协议比较多,通过我们使用Get或者Post的方法调用一个数据接口,然后服务器给我们返回JSON格式的数据,我们解析JSON数据然后展现给用户,相信很多人 ...
- 网络请求工具类WebServiceUtils
如果对WebService一无所知的话,建议先看看这两篇博客,对你WebService很有帮助. http://blog.csdn.NET/eyu8874521/article/details/912 ...
- 开发工具类API调用的代码示例合集:六位图片验证码生成、四位图片验证码生成、简单验证码识别等
以下示例代码适用于 www.apishop.net 网站下的API,使用本文提及的接口调用代码示例前,您需要先申请相应的API服务. 六位图片验证码生成:包括纯数字.小写字母.大写字母.大小写混合.数 ...
- Spring工具类
文件资源访问 1.统一资源访问接口 Resource 2.实现类 FileSystemResource 通过文件系统路径访问 ClassPathResource 通过classpath路径访问 Ser ...
- 突破CRUD | 万能树工具类封装
0.学完本文你或许可以收获 感受一个树工具从初始逐步优化完善的过程 树工具封装的设计思考与实现思路 最后收获一款拿来即用的树工具源代码 对于前端树组件有一定了解和使用过的同学可直接跳跃到第3章节开始. ...
随机推荐
- Linux 程序设计的一些优化措施
Linux 程序设计的一些优化措施 这些知识是在平常的阅读中,零散的获得的,自己总结了一下,分享在这里 全局变量VS函数参数 全局变量在Linux下的驱动编程里边,用的是非常多,例如中断服务函数ISR ...
- Android学习总结——去除标题栏
1.继承app.Activity的Activity去除标题栏 @Override protected void onCreate(Bundle savedInstanceState) { super. ...
- mvc初学controller参数传递感想
从视图中传递参数给controller也有很多种方式 方法一(推荐):路由 config.Routes.MapHttpRoute( name: "DefaultApi", rout ...
- uva 310 L--system(隐式图搜索+字符串处理)
L-system A D0L (Deterministic Lindenmayer system without interaction) system consists of a finite ...
- [Redux] Extracting Action Creators
We will create an anction creator to manage the dispatch actions, to keep code maintainable and self ...
- 免费自学Cocos2d-x3.0final2014原创视频教程(56集)(适用于Cocos2d-x3.1 Cocos2d-x3.2版本号全)
Cocos2d-x3.0final(适用于Cocos2d-x3.1 Cocos2d-x3.2版本号全) 视频播放地址:http://yun.itxdl.cn/course/62 视频下载地址:http ...
- MBTI性格测试
INFP 哲学家型——生活在自己的理想世界 报告接收人: 才储成员4361454 日期: 2014/9/2 一.你的MBTI图形 倾向示意图表示四个维度分别的倾向程度.从中间往两侧看,绿色指示条对应下 ...
- NFinal简介
NFinalWeb框架是基于魔法糖语法思想创建的框架.本框架有两大特点.1.所有框架里最简单易学易配置的.2.所有框架里运行效率最快的. 相关介绍1.运行效率比任何php和java以及.net框架要快 ...
- MongoDB学习笔记03
限制结果的返回数量可以使用limit.skip sort用一个对象作为参数:一组键/值对,键对应文档的键名,值代表排序的方向(1:升序,-1:降序):如果指定了多个键,则按照多个键的顺序诸个排序. M ...
- Intellij Idea 配置database 连接SQL Server 2012
首先确认通过TCP IP来连接连接SQLServer 2012 确保 Server Authentication选择了SQL Server and Windows Authentication ...