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

  1. Http请求 post get

    package com.sprucetec.tms.utils; import org.slf4j.Logger;import org.slf4j.LoggerFactory; import java ...

随机推荐

  1. 2018.12.15 bzoj3676: [Apio2014]回文串(后缀自动机)

    传送门 对原串建立一个后缀自动机,然后用反串在上面匹配. 如果当前匹配的区间[l,r][l,r][l,r]包裹了当前状态的endposendposendpos中的最大值,那么[l,maxpos][l, ...

  2. 2018.12.12 codeforces 935D. Fafa and Ancient Alphabet(概率dp)

    传送门 概率dp水题. 题意简述:给你数字表的大小和两个数列,数列中为0的数表示不确定,不为0的表示确定的,求第一个数列字典序比第二个数列大的概率. fif_ifi​表示第i ni~ ni n位第一个 ...

  3. 2018.11.09 洛谷P1110 [ZJOI2007]报表统计(multiset)

    传送门 sb题. 直接用两个multisetmultisetmultiset维护相邻两个数的差值和所有数的前驱后继. 插入一个数的时候更新一下就行了. 代码: #include<bits/std ...

  4. 创建视图&新建表按照视图结构

    create  view  V_tableTemp as  select a.* from TEMPCLIENT a ,TEMPCLIENTSTUFF b where a.CORNO<>' ...

  5. 证明 U and V={0}时 dim(U+V)=dim(U)+dim(V)

    U And V={0} 证明 dim(U+V)=dim(U)+dim(V)设{u1,u2,...,uk} 是U的基,{v1,v2...,vr}是V的基,dim(U)=k ,dim(V)=r dim(U ...

  6. JAVA作业之两数的加减乘除

    1.设计思路 把输入的字符转化为计算的数字问题,再以对话框的形式输入输出加减乘除的结果问题. 2.程序流程图 3.源代码 4.实验结果

  7. Q他中的乱码再理解

    Qt版本有用4的版本的也有用5的版本,并且还有windows与linux跨平台的需求. 经常出现个问题是windows的解决了,源代码放到linux上编译不通过或者中文会乱码,本文主要是得出一个解决方 ...

  8. 冲刺博客NO.5

    今天做了什么:布局UI和效果图,学会了监听事件并销毁监听接口 SMSSDK.unregisterAllEventHandler(); 今天做的东西不多,没有遇到什么苦难

  9. java基础知识-数据类型及转换

    1.java中的常量大体分为两种: <1>字面量常量 <2>自定义常量 2.java中常量(字面量)的分类:<1>,整数常量:直接出现的整数<2>,小数 ...

  10. RxSwift学习笔记5:Binder

    使用 Binder 创建观察者 //Observable序列(每隔1秒钟发出一个索引数) let scheduleObservable = Observable<Int>.interval ...