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 ...
随机推荐
- HDU 6129 Just do it
题意:给你一个包含n个数的序列A和一个数m,序列B中的数是序列A经过异或得到的,比如:b[i]=a[1]^a[2]^…..^a[i].现在让你求经过m次异或后,序列B的值. 思路:这题其实和杨辉三角 ...
- java.io.IOException: java.sql.SQLException: ORA-01502: index 'BTO.PK_xxxxx' or partition of such index is in unusable state
最近由于数据库的全备出问题了,所以一直在观察. 刚好发现很多不需要的数据,就删了几百个G的数据吧. 今天突然就报这个问题. java.io.IOException: java.sql.SQLExcep ...
- 2018.12.31 NOIP训练 偶数个5(简单数论)
传送门 对于出题人zxyoizxyoizxyoi先%\%%为敬题目需要龟速乘差评. 题意简述:5e55e55e5组数据,给出n,请你求出所有n位数中有偶数个5的有多少,n≤1e18n\le1e18n≤ ...
- python中下划线
引用:https://blog.csdn.net/tcx1992/article/details/80105645?from=timeline Python中下划线的5种含义 class A(obje ...
- AttributeError: type object 'testClass' has no attribute 'testMothod'
点击"Unittest for test_post_API.testClass"按钮,点击”Edit configuration...“,弹出对话框Run/Debug config ...
- s5-10 路由
路由器转发分组的依据 路由表 路由表从何而来 直连路由.静态路由.动态路由 路由器收到一个分组之后- 打开分组L3,提取出目的IP地址 确定目标网络,查找路由表 按位"AND&quo ...
- 【慕课网实战】Spark Streaming实时流处理项目实战笔记一之铭文升级版
第一章:课程介绍 铭文一级: VMware Fusion Mac上搭建:为了给大家演示如何使用我们的OOTB环境 Hadoop环境:虚拟机,我是远程登录 Mac 那么就不需要使用我们的OOTB环境 V ...
- ArcGIS的地理坐标系与大地坐标系
一直以来,总有很多朋友针对地理坐标系.大地坐标系这两个概念吃不透.近日,在网上看到一篇文章介绍它们,非常喜欢.所以在此转发一下,希望能够对制图的朋友们有所帮助. 地理坐标:为球面坐标. 参考平面地是 ...
- 查看Redis集群主从对应关系工具
工具的作用: 1)比"cluster nodes"更为直观的显示结果 2)指出落在同一个IP上的master 3)指出落在同一个IP上的master和slave对 运行效果图: 源 ...
- VC6.0编译器设置
主要通过VC的菜单项Project->Settings->C/C++页来完成.我们可以看到这一页的最下面Project Options中的内容,一般如下:/nologo /MDd /W3 ...