直接贴代码:

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的工具类的更多相关文章

  1. 使用HttpClient访问url的工具类

    maven依赖jar包配置: <dependency> <groupId>org.apache.httpcomponents</groupId> <artif ...

  2. 一、JDBC的概述 二、通过JDBC实现对数据的CRUD操作 三、封装JDBC访问数据的工具类 四、通过JDBC实现登陆和注册 五、防止SQL注入

    一.JDBC的概述###<1>概念 JDBC:java database connection ,java数据库连接技术 是java内部提供的一套操作数据库的接口(面向接口编程),实现对数 ...

  3. UrlUtils工具类,Java URL工具类,Java URL链接工具类

    UrlUtils工具类,Java URL工具类,Java URL链接工具类 >>>>>>>>>>>>>>>&g ...

  4. java服务器访问其他服务器工具类编写

    java服务器访问其他服务器工具类编写适合各种消息推送及微服务交互 package com.xiruo.medbid.components; import com.xiruo.medbid.util. ...

  5. 从零开始学android开发-通过WebService进行网络编程,使用工具类轻松实现

    相信大家在平常的开发中,对网络的操作用到HTTP协议比较多,通过我们使用Get或者Post的方法调用一个数据接口,然后服务器给我们返回JSON格式的数据,我们解析JSON数据然后展现给用户,相信很多人 ...

  6. 网络请求工具类WebServiceUtils

    如果对WebService一无所知的话,建议先看看这两篇博客,对你WebService很有帮助. http://blog.csdn.NET/eyu8874521/article/details/912 ...

  7. 开发工具类API调用的代码示例合集:六位图片验证码生成、四位图片验证码生成、简单验证码识别等

    以下示例代码适用于 www.apishop.net 网站下的API,使用本文提及的接口调用代码示例前,您需要先申请相应的API服务. 六位图片验证码生成:包括纯数字.小写字母.大写字母.大小写混合.数 ...

  8. Spring工具类

    文件资源访问 1.统一资源访问接口 Resource 2.实现类 FileSystemResource 通过文件系统路径访问 ClassPathResource 通过classpath路径访问 Ser ...

  9. 突破CRUD | 万能树工具类封装

    0.学完本文你或许可以收获 感受一个树工具从初始逐步优化完善的过程 树工具封装的设计思考与实现思路 最后收获一款拿来即用的树工具源代码 对于前端树组件有一定了解和使用过的同学可直接跳跃到第3章节开始. ...

随机推荐

  1. [RxJS] Reactive Programming - Why choose RxJS?

    RxJS is super when dealing with the dynamic value. Let's see an example which not using RxJS: var a ...

  2. BOOST 线程完全攻略 - 扩展 - 事务线程

    扩展threadtimermoduleexceptionsocket 什么叫事务线程 举个例子: 我们写一个IM客户端的登录子线程,则该子线程会有这么几个事务要处理 No.1 TCP Socket物理 ...

  3. iOS:UI系列之UINavigationController

    又到了总结的时间了,突然间感觉时间过得好快啊, 总觉的时间不够用,但是这也没办法啊, 只有自己挤时间了,虽然是零基础,但是这并不能代表什么啦,只要努力,收获总还是有的, 同时我也相信广大的博友肯定也有 ...

  4. 本博客弃用,请移步http://ningios.com查看最新

    本博客弃用,请移步http://ningios.com查看最新

  5. My way to Python - Day02

    版权声明: 本文中的资料均来自于互联网.将各路内容摘抄于此,作为学习笔记,方便用作后面翻阅查看.如果原作者对文中内容的引用有任何版权方面的问题,请随时联系,我将尽快处理. 特别鸣谢:武沛齐 <P ...

  6. Windows下安装Django及WEB服务启动

           如果使用的是 Linux 或 Mac OS X ,系统可能已经预装了 Python .在命令提示符下 (或 OS X 的终端中) 输入python ,如果出现python编辑环境,说明 ...

  7. 解决mysql中文存储问题

    在mysql安装目录下先找到my.ini,给[mysql]和[mysqld]下的default-character-set赋值为utf8 即改为:default-character-set=utf8 ...

  8. Ubuntu 12.04 LTS 构建高可用分布式 MySQL 集群

    本文的英文版本链接是 http://xuri.me/2013/11/20/install-mysql-cluster-on-ubuntu-12-04-lts.html MySQL Cluster 是 ...

  9. 将String转化为Long,并将Long转化为Date

    package org.ljh.test.javaee; import java.text.SimpleDateFormat; import java.util.Date; public class ...

  10. Java 一个字符串在另外一个字符串出现次数

    统计一个字符串在另外一个字符串出现次数 代码如下: package me.chunsheng.javatest; import java.util.regex.Matcher; import java ...