HttpInvokerUtils
package com.sprucetec.tms.utils; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL; /**
* HttpInvoker.
*
* @author Yinqiang Du
* @date 2016/8/11
*/
public class HttpInvokerUtils {
/**
* 日志.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(HttpInvokerUtils.class); /**
* 发起http get 请求获取返回结果.
*
* @param getURL 请求路径 .
* @return
* @throws Exception
*/
public static String sendGetRequest(String getURL) throws IOException {
// 拼凑get请求的URL字串,使用URLEncoder.encode对特殊和不可见字符进行编码
URL getUrl = new URL(getURL);
// 根据拼凑的URL,打开连接,URL.openConnection函数会根据 URL的类型,
// 返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) getUrl
.openConnection();
// 进行连接,但是实际上get request要在下一句的 connection.getInputStream()函数中才会真正发到
// 服务器
connection.connect();
// 取得输入流,并使用Reader读取
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
LOGGER.info(" ============================= ");
LOGGER.info(" Contents of get request ");
LOGGER.info(" ============================= ");
String lines="";
String temp="";
while ((temp = reader.readLine()) != null) {
lines += temp;
}
reader.close();
// 断开连接
connection.disconnect();
LOGGER.info(" ============================= ");
LOGGER.info(" Contents of get request ends ");
LOGGER.info(" ============================= ");
return lines;
} /**
* 发起http post 请求获取返回结果.
*
* @param urlStr 请求路径 .
* @param requestParamsJson json字符串.
* @return
* @throws Exception
*/
public static String sendPostRequest(String urlStr, String requestParamsJson) throws Exception {
LOGGER.info(" ============================= ");
LOGGER.info("开始发送http post请求...");
LOGGER.info(" ============================= ");
BufferedOutputStream bufOutPut = null;
BufferedReader bufferedReader = null;
HttpURLConnection httpConn = null;
String lines = "";
try {
URL url = new URL(urlStr);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setDoInput(true); // 设置是否从httpUrlConnection读入,默认情况下是true;
httpConn.setDoOutput(true); // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
httpConn.setRequestMethod("POST");// 设定请求的方法为"POST",默认是GET
httpConn.setAllowUserInteraction(false); //是否允许用户交互
httpConn.setUseCaches(false); // Post 请求不能使用缓存
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestProperty("Accept-Charset", "UTF-8");
httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
httpConn.setRequestProperty("Content-Type", "application/json"); // 设定传送的内容类型是可序列化的java对象
// 此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,
bufOutPut = new BufferedOutputStream(httpConn.getOutputStream());
httpConn.connect();
byte[] bdat = requestParamsJson.getBytes("UTF-8");// 解决中文乱码问题
bufOutPut.write(bdat, 0, bdat.length);
bufOutPut.flush(); // 根据ResponseCode判断连接是否成功
int responseCode = httpConn.getResponseCode();
if (responseCode != 200) {
LOGGER.error(" Error===" + responseCode);
} else {
LOGGER.info("Post Success!");
}
// 定义BufferedReader输入流来读取URL的ResponseData
bufferedReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String temp = "";
while ((temp = bufferedReader.readLine()) != null) {
lines += temp;
}
} catch (Exception e) {
LOGGER.error("send post request error!" + e);
} finally {
httpConn.disconnect(); // 断开连接
try {
if (bufOutPut != null) {
bufOutPut.close();
}
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
LOGGER.info(" ============================= ");
LOGGER.info("发送http post请求结束...");
LOGGER.info(" ============================= ");
return lines;
}
}
HttpInvokerUtils的更多相关文章
- Http请求 post get
package com.sprucetec.tms.utils; import org.slf4j.Logger;import org.slf4j.LoggerFactory; import java ...
随机推荐
- JS基础-数据类型-运算符和表达式-变量和常量
1.js的基础语法2.js调试 1.F12调出控制台,查看提示错误及其位置. 2.出错时只影响当前代码块,不会影响其他代码块,后续代码块继续执行.3.语法规范 1.js语句:可执行的最小单元 必须以 ...
- 【转】如何用Redis做LRU-Cache
LRU(Least Recently Used)最近最少使用算法是众多置换算法中的一种. Redis中有一个maxmemory概念,主要是为了将使用的内存限定在一个固定的大小.Redis用到的LRU ...
- 2018.12.31 bzoj3992: [SDOI2015]序列统计(生成函数+ntt+快速幂)
传送门 生成函数简单题. 题意:给出一个集合A={a1,a2,...as}A=\{a_1,a_2,...a_s\}A={a1,a2,...as},所有数都在[0,m−1][0,m-1][0,m− ...
- flask 知识积累
PythonWEB框架之Flask Flask快速入门,知识整理 Flask 框架
- GreenPlum 初始化配置报错:gpadmin-[ERROR]:-[Errno 12] Cannot allocate memory
报错原因:可能swap太小或者没有交换分区 解决方法: (1)查看swap:swapon -s (2)如果什么都没有显示,说明你没有任何可用的swap,此时你可以添加1GB的swap: dd if=/ ...
- C中的volatile用法[转载]
volatile 影响编译器编译的结果,指出,volatile 变量是随时可能发生变化的,与volatile变量有关的运算,不要进行编译优化,以免出错,(VC++ 在产生release版可执行码时会进 ...
- python3 print函数的用法
1. 输出字符串 >>> strHello = 'Hello World' >>> print (strHello) Hello World 2. 格式化输出整数 ...
- CDATASection类型——数据采集
CDATASection类型只针对基于XML的文档,表示的是CDATA区域 CDATASection类型和comment类型都是继承自基于Text类型,除了splitText()之外的所有字符串方法 ...
- mysql主从复制Error1205
主从架构.今天发现从库SQL线程报错,主从复制停止了.查看错误发现: Last_SQL_Errno: 1205 Last_SQL_Error: Slave SQL thread ...
- redis.conf之save配置项解读
配置示例: save 900 1 save 300 10 save 60 3600 配置解读: 1) “save 900 1”表示如果900秒内至少1个key发生变化(新增.修改和删除),则重写rdb ...