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 ...
随机推荐
- mybatis学习七 typeAliases 别名
1. mybatis中内置的一些别名,例如Map,List,int 等常用类型 2.手动为某个类设置别名 在mybatis的全局配置文件中加如下代码 <typeAliases> <t ...
- 20155312 2006-2007-2 《Java程序设计》第二周学习总结
20155312 2006-2007-2 <Java程序设计>第二周学习总结 课堂内容总结 git:版本控制 生活中的容灾备份 归纳思维.实验思维.计算思维 计算机:实现自动化 学会使用快 ...
- python下使用opencv拍照
首先在命令中安装opencv: pip install opencv-python 然后打开notebook: jupyter notebook 建立文件,写入如下代码: import cv2 cap ...
- 44、WebStrom下载和破解
WebStrom下载地址: http://www.pc6.com/mac/112553.html WebStrom 2017激活破解(http://blog.csdn.net/it_talk/arti ...
- 2019.02.06 bzoj2987: Earthquake(类欧几里得)
传送门 题意简述:求满足ax+by+c≤0ax+by+c\le0ax+by+c≤0的二元组(x,y)(x,y)(x,y)对数. 思路: 类欧几里得算法模板题. 把式子变化一下变成:求满足0≤y≤−ax ...
- 2018.11.06 bzoj1097: [POI2007]旅游景点atr(最短路+状压dp)
传送门 预处理出不能在每个点停留之后才停留的点的状态. 对kkk个点都跑一次最短路存下来之后只需要简单状压一下就能过了吐槽原题空间64MB蒟蒻无能为力 然后用fillfillfill赋极大值的时候当m ...
- 新建maven遇到的错误
新建一个maven,遇到错误如下: Description Resource Path Location Type Dynamic Web Module 3.0 requires Java 这时候,只 ...
- DOS的几个常用命令
1.rem:注释 DOS中的注释,其后面的内容会被自动忽略.双冒号(::)也有相同的效果 相当于R语言和Python中的# 2.set:设置变量 set var = 1 将1赋值给变量var 打印出来 ...
- java 块语句 和引用类型
1.java中存在块语句,块语句分为四种 1.静态块 2.普通块 3.构造块 4.同步块 静态块的执行时机是在class文件装载的时候;静态块只会执行一次, 多个静态块的时候,按出现顺序执行,存放类的 ...
- 安装postgis,使用postgis导入shapefile的步骤总结
最近在做开源WebGIS方面的工作,要使用postgis导入shapefile数据.难点在安装过程和导入时命令行参数的使用,以下分别作个介绍,希望对大家有点用 一.安装postgis (1)首先到po ...