1,导入依赖

        <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
       <version>4.5.12</version>
</dependency>

2,http发送请求工具类

@Value("${spring.profiles.active}")  获取配置文件中对应的值
注解很详细
package com.hl.analyze.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.integration.utils.DateUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import java.io.IOException;
import java.net.URI;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors; /**
* @program: sgitg-micro-service
* @description: HttpClient工具类
**/
@Component
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class HttpClientUtil {
private static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class); private final static String ACTIVE_TAG = "dev";
private static String active;
private static String loginUrl;
private static String loginUrlNew;
private static String userName;
private static String userNameNew;
private static String passWord;
private static String passWordNew;
private static String distributedPredictUrl;
private static String distribsunStationUrl; @Value("${spring.profiles.active}")
public void setActive(String active) {
HttpClientUtil.active = active;
} @Value("${hlkj.new-power-sys.login-url}")
public void setLoginUrl(String loginUrl) {
HttpClientUtil.loginUrl = loginUrl;
}
@Value("${hlkj.new-power-sys.login-url-new}")
public void setLoginUrlNew(String loginUrl) {
HttpClientUtil.loginUrlNew = loginUrl;
} @Value("${hlkj.new-power-sys.user-name}")
public void setUserName(String userName) {
HttpClientUtil.userName = userName;
}
@Value("${hlkj.new-power-sys.user-name-new}")
public void setUserNameNew(String userName) {
HttpClientUtil.userNameNew = userName;
} @Value("${hlkj.new-power-sys.pass-word}")
public void setPassWord(String passWord) {
HttpClientUtil.passWord = passWord;
}
@Value("${hlkj.new-power-sys.pass-word-new}")
public void setPassWordNew(String passWord) {
HttpClientUtil.passWordNew = passWord;
} @Value("${hlkj.new-power-sys.distributed-predict-url}")
public void setDistributedPredictUrl(String distributedPredictUrl) {
HttpClientUtil.distributedPredictUrl = distributedPredictUrl;
} @Value("${hlkj.new-power-sys.distribsun-station-url}")
public void setDistribsunStationUrl(String distribsunStationUrl) {
HttpClientUtil.distribsunStationUrl = distribsunStationUrl;
} /**
* @return java.lang.String
* @Description get map参数
* @Date 2020/12/8 13:56
* @Param [url, param]
**/
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build(); // 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
httpclient.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
return resultString;
} public static String doGet(String url, Map<String, String> headMap, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build(); // 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
// 添加head参数
if (headMap != null && !headMap.isEmpty()) {
for (String key : headMap.keySet()) {
httpGet.addHeader(key, headMap.get(key));
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
httpclient.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
return resultString;
} /**
* @return java.lang.String
* @Description get无参
* @Date 2020/12/8 13:56
* @Param [url]
**/
public static String doGet(String url) {
return doGet(url, null);
} /**
* @return java.lang.String
* @Description post map参数
* @Date 2020/12/8 13:56
* @Param [url, param]
**/
public static String doPost(String url, Map<String, String> param) {
log.debug("接口地址【{}】", url);
log.debug("接口参数【{}】", param);
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
httpPost.setEntity(entity);
httpPost.setHeader("sppp-id", "fe8de0-3749-43b1-9b7e-e652763a682d");
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
httpClient.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
log.debug("接口返回值【{}】", resultString);
return resultString;
} public static Header[] doPostForHeader(String url, Map<String, String> param) {
log.debug("接口地址【{}】", url);
log.debug("接口参数【{}】", param);
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
Header[] allHeaders = new Header[0];
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
httpPost.setEntity(entity);
httpPost.setHeader("sppp-id", "fe8de0-3749-43b1-9b7e-e652763a682d");
}
// 执行http请求
response = httpClient.execute(httpPost);
allHeaders = response.getAllHeaders();
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
httpClient.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
log.debug("返回值【{}】", allHeaders);
return allHeaders;
} /**
* @return java.lang.String
* @Description post head map参数
* @Date 2021/04/28 15:15
* @Param [url, headMap, param]
**/
public static String doPost(String url, Map<String, String> headMap, Map<String, String> param) {
log.debug("接口地址【{}】", url);
log.debug("接口参数【{}】", param);
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
httpPost.setEntity(entity);
}
// 添加head参数
if (headMap != null && !headMap.isEmpty()) {
for (String key : headMap.keySet()) {
httpPost.addHeader(key, headMap.get(key));
}
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
httpClient.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
log.debug("接口返回值【{}】", resultString);
return resultString;
} public static String doPostByFormData(String url, Map<String, String> param) throws Exception {
log.debug("接口地址【{}】", url);
log.debug("接口参数【{}】", param);
String result = "";
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(5000)
.setConnectionRequestTimeout(6000).setStaleConnectionCheckEnabled(true).build();
client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
// client = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder(url); HttpPost httpPost = new HttpPost(uriBuilder.build());
httpPost.setHeader("Connection", "Keep-Alive");
httpPost.setHeader("Charset", "UTF-8");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
Iterator<Map.Entry<String, String>> it = param.entrySet().iterator();
List<NameValuePair> params = new ArrayList<NameValuePair>(); while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
params.add(pair);
} httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
try {
response = client.execute(httpPost);
if (response != null) {
log.debug("response 为空");
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
log.debug("resEntity 为空");
result = EntityUtils.toString(resEntity, "UTF-8");
}
}
} catch (ClientProtocolException e) {
throw new RuntimeException("创建连接失败" + e);
} catch (IOException e) {
throw new RuntimeException("创建连接失败" + e);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
client.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
log.debug("接口返回值【{}】", result);
return result;
} public static String doPost(String url) {
return doPost(url, null);
} /**
* @return java.lang.String
* @Description post json参数
* @Date 2020/12/8 13:56
* @Param [url, param]
**/
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
httpClient.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
return resultString;
} public static String doPostJson(String url, Map<String, String> headMap, String json) {
log.info("请求地址:{}",url);
log.info("请求头:{}",headMap);
log.info("请求参数:{}",json);
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 添加head参数
if (headMap != null && !headMap.isEmpty()) {
for (String key : headMap.keySet()) {
httpPost.addHeader(key, headMap.get(key));
}
}
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
httpClient.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
log.info("返回值:{}",resultString);
return resultString;
} public static String getNewPowerSysCookie() {
if (ACTIVE_TAG.equals(active)) {
return "cookie";
} else {
try {
Header[] headers = HttpClientUtil.doPostForHeader(loginUrl, new HashMap<String, String>() {{
put("username", userName);
put("password", passWord);
}});
Map<Object, Object> objectMap = Arrays.stream(headers).collect(Collectors.toMap(NameValuePair::getName, NameValuePair::getValue, (e1, e2) -> e1));
String cookie = objectMap.get("Set-Cookie").toString();
log.debug(String.valueOf(objectMap));
log.debug("date:{}====================cookie:{}===========", LocalDateTime.now(), cookie);
return cookie;
}catch (Exception e){
e.printStackTrace();
log.error("新能源接口异常,请检查新能源系统是否正常!");
return "null";
}
} }
public static String getAuthorization() {
if (ACTIVE_TAG.equals(active)) {
return "Authorization";
} else {
try {
log.info("userNameNew=" + userNameNew);
log.info("passWordNew=" + passWordNew);
log.info("loginUrlNew=" + loginUrlNew);
Header[] headers = HttpClientUtil.doPostForHeader(loginUrlNew, new HashMap<String, String>() {{
put("username", userNameNew);
put("password", passWordNew);
put("type", "0");
}});
log.info("headers=" + headers.toString());
String res = HttpClientUtil.doPost(loginUrlNew, new HashMap<String, String>() {{
put("username", userNameNew);
put("password", passWordNew);
put("type", "0");
}});
log.info("loginUrlNewRes=" + String.valueOf(res));
JSONObject jsonObject = JSONObject.parseObject(res);
String token = jsonObject.get("token").toString();
String Authorization = "Bearer " + token;
/*Map<Object, Object> objectMap = Arrays.stream(headers).collect(Collectors.toMap(NameValuePair::getName, NameValuePair::getValue, (e1, e2) -> e1));
String cookie = objectMap.get("Set-Cookie").toString();*/
log.info("AuthorizationSet=" + String.valueOf(Authorization));
log.info("date:{}====================cookie:{}===========", LocalDateTime.now(), Authorization);
return Authorization;
}catch (Exception e){
e.printStackTrace();
log.error("可开放容量监测接口异常,请检查新能源系统是否正常!");
return "null";
}
}
} public static String getNewEnergyPower(String scheduleId, String scheduleName) {
if (ACTIVE_TAG.equals(active)) {
return "222.33";
} else {
// 德州所有用户在某刻的瞬时功率
String realTimePower = "";
// 获取token
String newPowerSysCookie = HttpClientUtil.getNewPowerSysCookie();
try {
Map<String, String> map = Maps.newHashMapWithExpectedSize(6);
Map<String, String> hMap = Maps.newHashMapWithExpectedSize(6); map.put("scheduleId", scheduleId);
map.put("scheduleName", scheduleName);
map.put("beginTime", com.integration.utils.DateUtils.parseDate(new Date(), "yyyy-MM-dd"));
map.put("endTime", com.integration.utils.DateUtils.parseDate(new Date(), "yyyy-MM-dd"));
map.put("distribsunStationId", "");
map.put("distribsunStationName", ""); hMap.put("Cookie", newPowerSysCookie);
// 接口返回值
String postRes = HttpClientUtil.doPost(distributedPredictUrl, hMap, map); JSONObject objMap = (JSONObject) JSONObject.parseObject(postRes).get("obj");
JSONArray lineData = (JSONArray) objMap.get("linedata");
JSONArray tabledata = (JSONArray) objMap.get("tabledata"); Double value = 0.0;
for (int i = 0; i < tabledata.size(); i++) {
JSONObject data = (JSONObject) tabledata.get(i);
String hours = data.get("time").toString();
// 当前是几点
String nowHours = DateUtils.parseDate(new Date(), "yyyy-MM-dd HH:mm:ss").split(" ")[1].split(":")[0];
if (hours.contains(nowHours + ":00:00")) {
value = value + Double.parseDouble("-".equals(data.get("data").toString())?"0":data.get("data").toString());
log.debug("德州所有用户的的瞬时功率值:{}", value);
break;
}
}
if (value == 0.0) {
realTimePower = lineData.get(lineData.indexOf("-") - 1).toString();
} else {
DecimalFormat decimalFormat = new DecimalFormat("0.00");
realTimePower = decimalFormat.format(value);
} } catch (Exception e) {
log.error("新能源接口异常" + e.getMessage(), e);
}
return realTimePower;
}
} }
 

java发送http请求get/post的更多相关文章

  1. Java发送Http请求并获取状态码

    通过Java发送url请求,查看该url是否有效,这时我们可以通过获取状态码来判断. try { URL u = new URL("http://10.1.2.8:8080/fqz/page ...

  2. 通过java发送http请求

    通常的http请求都是由用户点击某个连接或者按钮来发起的,但是在一些后台的Java程序中需要发送一些get或这post请求,因为不涉及前台页面,该怎么办呢? 下面为大家提供一个Java发送http请求 ...

  3. Java发送HTTPS请求

    前言 上篇文章介绍了 java 发送 http 请求,大家都知道发送http是不安全的 .我也是由于对接了其他企业后总结了一套发送 https的工具.大家网上找方法很多的,但是可不是你粘过来就能用啊, ...

  4. 使用Java发送Http请求的内容

    公司要将自己的产品封装一个WebService平台,所以最近开始学习使用Java发送Http请求的内容.这一块之前用PHP的时候写的也比较多,从用最基本的Socket和使用第三方插件都用过. 学习了J ...

  5. Java发送socket请求的工具

    package com.tech.jin.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import ...

  6. Java发送Http请求

    package com.liuyu.test; import java.io.BufferedReader; import java.io.IOException; import java.io.In ...

  7. 编写爬虫(spider)的预备知识:用java发送HTTP请求

    使用原生API来发送http请求,而不是使用apache的库,原因在于这个第三方库变化实在太快了,每个版本都有不小的变化.对于程序员来说,使用它反而会有很多麻烦,比如自己曾经写过的代码将无法复用. 原 ...

  8. Java发送post请求

    package com.baoxiu.test; import java.io.BufferedReader;import java.io.InputStreamReader;import java. ...

  9. java发送post请求 ,请求数据放到body里

    java利用httpclient发送post请求 ,请求数据放到body里. /** * post请求 ,请求数据放到body里 * * @author lifq * * 2017年3月15日 下午3 ...

  10. JAVA发送HttpClient请求及接收请求结果

    1.写一个HttpRequestUtils工具类,包括post请求和get请求 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 2 ...

随机推荐

  1. 《手把手教你》系列基础篇(九十七)-java+ selenium自动化测试-框架设计篇-Selenium方法的二次封装和页面基类(详解教程)

    1.简介 上一篇宏哥介绍了如何设计支持不同浏览器测试,宏哥的方法就是通过来切换配置文件设置的浏览器名称的值,来确定启动什么浏览器进行脚本测试.宏哥将这个叫做浏览器引擎类.这个类负责获取浏览器类型和启动 ...

  2. OpenHarmony 3GPP协议开发深度剖析——一文读懂RIL

    (以下内容来自开发者分享,不代表 OpenHarmony 项目群工作委员会观点)本文转载自:https://harmonyos.51cto.com/posts/10608 夏德旺 软通动力信息技术(集 ...

  3. this-2

    读起来使你有新认识或可以使你离更确切的定义更近时的文章不应该被忽略.thisthis既不指向函数自身,也不指向函数的词法作用域(ES6中箭头函数采用词法作用域).this实际上是函数被调用时才发生绑定 ...

  4. UDP协议、操作系统、同步与异步、阻塞与非阻塞

    UDP协议 # 客户端 import socket server = socket.socket(type=socket.SOCK_DGRAM) server.bind(('127.0.0.1', 8 ...

  5. 基于dhtmlxGantt的Blazor甘特图组件

    基于dhtmlxGantt实现的甘特图组件,目前仅做到了数据展现,方法及插槽暂未实现,若需可按照dhtmlxGantt的文档及微软的Balzor文档,自行扩展. 数据发生变化后甘特图会立即发生变化. ...

  6. AngularJS搭建环境

    一.搭建环境 1.1 调试工具:batarang Chrome浏览器插件 主要功能:查看作用域.输出高度信息.性能监控 1.2 依赖软件:Node.js 下载:https://nodejs.org/e ...

  7. 探究MySQL中SQL查询的成本

    成本 什么是成本,即SQL进行查询的花费的时间成本,包含IO成本和CPU成本. IO成本:即将数据页从硬盘中读取到内存中的读取时间成本.通常1页就是1.0的成本. CPU成本:即是读取和检测是否满足条 ...

  8. Java中如何快捷的创建不可变集合

    在Java 9中又新增了一些API来帮助便捷的创建不可变集合,以减少代码复杂度. 本期配套视频:Java 9 新特性:快速定义不可变集合 常规写法 以往我们创建一些不可变集合的时候,通常是这样写的: ...

  9. 微信小程序避坑指南——input框里的图标在部分安卓机里无法点击的问题

    问题场景: 下图中的显隐密码和验证码均为包裹在 input标签 中的 image标签, 但在开发测试中发现点击不了这俩个image标签,因为是被input标签的padding挡住了. 解决方法:将im ...

  10. 重载overload 、重写override

    观点:重载和重写完全没有关系要联系到一起,唯一的联系就是他们都带有个'重'字,所以鄙人也随大流把他们放在了一起 注意:下面可复制的代码是正确的,错误的只会上传图片,不上传可复制的代码 重载 1.在同一 ...