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. iOS中堆和栈的区别

    管理方式: 对于栈来讲,是由编译器自动管理,无需我们手工控制:对于堆来讲,释放工作有程序员控制,容易产生memory Leak. 申请大小: 栈:在Windows下,栈是向低地址扩展的数据结构,是一块 ...

  2. day09作业—函数进阶

    # 2.写函数,接收n个数字,求这些参数数字的和.(动态传参) def func1(*args): sum = 0 for i in args: sum += i print(sum) func1(1 ...

  3. lambda表达式和表达式树(深入理解c#)

    1.Lambda形式 1). Lambda表达式最冗长的形式: (显式类型的参数列表)=>{语句} 2). 大多数时候,都可以用一个表达式来表示主体,该表达式的值是Lambda的结果,在这些情况 ...

  4. mysql安装后初始密码

    在安装过程中没有任何提示,安装完之后无法登陆 后经查询发现,可以暂时以 mysql -u root -p登陆 此账户没有密码直接enter即可. update user set Password=PA ...

  5. 树莓派无法挂载exfat格式硬盘

    ubutnu系统 挂载硬盘时报错: mount: unknown filesystem type 'exfat' 这是因为树莓派默认无法识别 exfat, 需要安装 exfat-fuse . sudo ...

  6. Codeforces gym 102062 简要题解

    文章目录 A. Bob and BoB B. Vibranium Gift C. The Blood Moon D. Palindrome and Chocolate E. Jumpy Robot F ...

  7. ThinkPHP 二维码生成

    请求获取并展示二维码 <img src="<?php echo U('createCode?zsnumber='.$time.$kcname['id'].$stuInfo['id ...

  8. excel中vba求摩尔圆包线

    Dim f As Double, f1 As Double, f2 As Double, df As Double, oxy() As Double, R() As Double, k As Doub ...

  9. highcharts x轴中文刻度太长换行

    xAxis: { type: 'category', title:null, gridLineWidth: 1, lineColor: "#50ae93", labels: { s ...

  10. 20155205 《Java程序设计》实验二(Java面向对象程序设计)实验报告

    20155205 <Java程序设计>实验二(Java面向对象程序设计)实验报告 一.实验内容及步骤 (一)单元测试 (1)三种代码 举例:我们要在一个MyUtil类中解决一个百分制成绩转 ...