import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;

/**
* @Author: 冯崇
* @Version:V1.0
*/
public class HttpRequestUtil {

protected static final Logger log = Logger.getLogger(HttpRequestUtil.class);

/**
* HttpClient 模拟POST请求 方法说明
*
* @Discription:扩展说明
* @param url
* @param params
* @return String
*/
public static String postRequest(String url, Map<String, String> params) {
//构造HttpClient的实例
HttpClient httpClient = new HttpClient();

//创建POST方法的实例
PostMethod postMethod = new PostMethod(url);

//设置请求头信息
postMethod.setRequestHeader("Connection", "close");

//添加参数
for (Map.Entry<String, String> entry : params.entrySet()) {
postMethod.addParameter(entry.getKey(), entry.getValue());
}

//使用系统提供的默认的恢复策略,设置请求重试处理,用的是默认的重试处理:请求三次
httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);

//接收处理结果
String result = null;
try {
//执行Http Post请求
httpClient.executeMethod(postMethod);

//返回处理结果
result = postMethod.getResponseBodyAsString();
} catch (HttpException e) {
// 发生致命的异常,可能是协议不对或者返回的内容有问题
log.error("请检查输入的URL: {}", e);
e.printStackTrace();
} catch (IOException e) {
// 发生网络异常
log.error("发生网络异常: {}", e);
e.printStackTrace();
} finally {
//释放链接
postMethod.releaseConnection();

//关闭HttpClient实例
if (httpClient != null) {
((SimpleHttpConnectionManager) httpClient.getHttpConnectionManager()).shutdown();
httpClient = null;
}
}
return result;
}

/**
* HttpClient 模拟GET请求 方法说明
*
* @Discription:扩展说明
* @param url
* @param params
* @return String
*/
public static String getRequest(String url, Map<String, String> params) {
//构造HttpClient实例
HttpClient client = new HttpClient();

//拼接参数
String paramStr = "";
for (String key : params.keySet()) {
paramStr = paramStr + "&" + key + "=" + params.get(key);
}
paramStr = paramStr.substring(1);
try {
paramStr = URLEncoder.encode(paramStr, "utf-8");
} catch (UnsupportedEncodingException e1) {
log.error("请检查输入的URL: {}", e1);
}
//创建GET方法的实例
GetMethod method = new GetMethod(url + "?" + paramStr);

//接收返回结果
String result = null;
try {
//执行HTTP GET方法请求
client.executeMethod(method);

//返回处理结果
result = method.getResponseBodyAsString();
} catch (HttpException e) {
// 发生致命的异常,可能是协议不对或者返回的内容有问题
log.error("请检查输入的URL: {}", e);
e.printStackTrace();
} catch (IOException e) {
// 发生网络异常
log.error("https请求异常: {}", e);
e.printStackTrace();
} finally {
//释放链接
method.releaseConnection();

//关闭HttpClient实例
if (client != null) {
((SimpleHttpConnectionManager) client.getHttpConnectionManager()).shutdown();
client = null;
}
}
return result;
}

/**
* PSOT方式发送HTTP请求
*
* @param url 请求地址
* @param data 请求参数
*/
public static String post(String url, String data) {
HttpURLConnection http = null;
PrintWriter out = null;
BufferedReader reader = null;
try {
//创建连接
URL urlPost = new URL(url);
http = (HttpURLConnection) urlPost.openConnection();
http.setDoOutput(true);
http.setDoInput(true);
http.setRequestMethod("POST");
http.setUseCaches(false);
http.setInstanceFollowRedirects(true);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

http.connect();

//POST请求
OutputStreamWriter outWriter = new OutputStreamWriter(http.getOutputStream(), "utf-8");
out = new PrintWriter(outWriter);
out.print(data);
out.flush();
out.close();
out = null;

//读取响应
reader = new BufferedReader(new InputStreamReader(http.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
reader.close();
reader = null;
// System.out.println(sb.toString());
return sb.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
return null;
} finally {
if (null != http) http.disconnect();
if (null != out) out.close();
try {
if (null != reader) reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* PSOT方式发送HTTP请求
*
* @param requestUrl 请求地址
* @param outputStr 请求参数
*/
public static JSONObject httpPostRequest(String requestUrl, String outputStr) {
PostMethod post = new PostMethod(requestUrl);
post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
post.addParameter("para", outputStr);
String info = null;
HttpClient httpclient = new HttpClient();
try {
httpclient.executeMethod(post);
info = new String(post.getResponseBody(), "UTF-8");
} catch (Exception e) {
log.error("https请求异常: {}", e);
}
// System.out.println(info);
return JSONObject.fromObject(info);
}

}

httpclient使用用例的更多相关文章

  1. [转]PROC简单使用用例--VC连接ORACLE

    [转]PROC简单使用用例--VC连接ORACLE 操作系统:windows 7 数据库版本:oracle 10g VS版本:VS2010 前言:连接ORACLE的方式有很多,此处仅以PROC为例,说 ...

  2. UML和模式应用4:初始阶段(6)--迭代方法中如何使用用例

    1.前言 用例是UP和其他众多迭代方法的核心.UP提倡用例驱动开发. 2. 迭代方法中如何使用用例 功能需求首先定义在用例中 用例是迭代计划的重要部分,迭代是通过选择一些用例场景或整个用例来定义的 用 ...

  3. GCOV 使用用例

      1.GCOV查看arm-linux代码覆盖率 一.           关于gcov工具 gcov伴随gcc 发布.gcc编译加入-fprofile-arcs -ftest-coverage 参数 ...

  4. nanosleep() -- 更精确的延迟 -----一个使用用例

    [常规] nanosleep() -- 更精确的延迟 [复制链接]     beyes 4220 主题 5152 帖子 3万 积分 GROAD 曲径通幽,安觅芳踪. 积分 30607 发消息 电梯直达 ...

  5. 在Visual Studio中使用用例图描述参与者与用例的关系

    在"在Visual Studio中使用用例图描述系统与参与者间的关系"中,使用用例图表示参与者与系统的关系,本篇体验参与者与用例(参与者要做的事情)的关系. 首先创建有关Custo ...

  6. 如何让classmethod只允许使用用类对象来调用

    Django REST framework里面有这样一段代码,在网上查@classonlymethod的意思是使得classmethod只允许使用用类对象来调用 @classonlymethod de ...

  7. 尽量少嵌套无用的div;外部文件尽量使用link而不要使用用@import

    最近的工作又学到了很多东西,在这里记录一下. 1,尽量少嵌套无用的div,这个问题领导很严肃的跟我提过很多次,因为我很喜欢用很多div,而且有很多div都是无存在意义的.后来领导给了我一些资料,我看了 ...

  8. 使用用树莓派打造远程WEB服务器

    简介:系统配置Raspberry Pi 3B + Raspbian + MySQL5.7 + Tomcat 9 + Nginx + 公网IP. 工具:Win32DiskImager .FileZill ...

  9. 使用用Generic.xaml加载默认的主题资源

    把Resource嵌入到Generic.xaml文件中,并把该文件放到应用程序的Themes主题文件夹下面,这们Generic.xaml文件中的资源就可以被系统识别为默认主题一部分,从而进行使用. 为 ...

随机推荐

  1. Swoole 结合TP5搭建文字直播平台

    直播模块流程: 主进程服务:主进程同时开启两个服务 http服务,负责向前端传递页面,处理登录等事务 websocket服务,服务处理直播以及聊天室等事务 在项目根目录(框架代码同级目录)建立scri ...

  2. [记录] CSS 左边元素定长,右边元素获得剩余长度

    情景:左边元素定长,右边元素获得剩余长度 1. 左边设置浮动,右边元素宽度auto,可以不设置,默认auto,然后设置margin-left:左边元素宽度 <ul class="ent ...

  3. Django的路由层详情

    1. Django的路由解析: 是从上往下进行匹配的 url(r'index', views.index) #这里的index 解析都可以被解析到的, abcindex index indexabc ...

  4. ---github git clone 加速

    https://www.zhihu.com/question/27159393/answer/35528173 git config --global http.postBuffer 52428800 ...

  5. Web安全颜色

    Web安全色产生的原因 不同的平台(Mac.PC等)有不同的调色板,不同的浏览器也有自己的调色板.这就意味着对于一幅图,显示在Mac上的Web浏览器中的图像,与它在PC上相同浏览器中显示的效果可能差别 ...

  6. NAT与FULL NAT的区别

    LVS 当前应用主要采用 DR 和 NAT 模式,但这 2 种模式要求 RealServer 和 LVS在同一个 vlan中,导致部署成本过高:TUNNEL 模式虽然可以跨 vlan,但RealSer ...

  7. Redis进阶实践之九 独立封装的RedisClient客户端工具类(转载9)

    Redis进阶实践之九 独立封装的RedisClient客户端工具类 一.引言 今天开始有关Redis学习的第九篇文章了,以后肯定会大量系统使用Redis作为缓存介质,为了更好的更好的Redis,自己 ...

  8. wx小程序自定义组件与页面之间参数传递

    在开发中,很多页面中会使用相同的组件,这时可以将具有相同信息的部分封装成一个组件,方便开发中调用.在调用中可能会涉及到数据的传递问题,例如页面与组件,组件与组件直接的数据传递. 首先看看页面与组件直接 ...

  9. mysql如何出查出最近7天,最近30天,最近n天的记录?

    已查询浏览量为例:原始数据如下: 思路分析:数据有了,统计某一天的浏览量,所有浏览量,或固定时间段内的浏览量在这里我们就不多说了,大家都会,那我们是如何将最近七天的数据统计出来呢? 首先,我们说的最近 ...

  10. DBCC维护语句语法

    一.DBCC维护语句:对数据库.索引或文件组进行维护的任务--1.DBCC CLEANTABLE,回收删除的可变长度列和文本列的空间 DBCC CLEANTABLE  ( { 'database_na ...