使用apache的:
package com.csgholding.pvgpsp.eqp.util;
import com.esotericsoftware.minlog.Log;
import org.apache.commons.collections4.MapUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
/**
* @Classname HttpClientUtil
* @Date 2021/5/11 8:45
* @Created by jj.Zhou
*/
public class HttpClientUtil {
//字符集
private static final String CHARSET = "UTF-8";
private static RequestConfig defaultRequestConfig = RequestConfig
.custom()
//设置等待数据超时时间
.setSocketTimeout(300000)
//设置连接超时时间
.setConnectTimeout(300000)
//设置从连接池获取连接的等待超时时间
.setConnectionRequestTimeout(300000)
//.setStaleConnectionCheckEnabled(true)
.build();
//释放资源,httpResponse为响应流,httpClient为请求客户端
private static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
if (httpResponse != null) {
httpResponse.close();
}
if (httpClient != null) {
httpClient.close();
}
}
//get请求带参数、带请求头
public static String getAndJson(String urlWithParams, Map header, Map param) throws URISyntaxException {
// 创建uri
URIBuilder builder = new URIBuilder(urlWithParams);
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);
if (!MapUtils.isEmpty(header)) {
header.forEach(httpGet::addHeader);
}
CloseableHttpClient httpClient = null;
String result;
try {
httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, CHARSET);
httpGet.releaseConnection();
release(response, httpClient);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (Exception e) {
Log.error(e.getMessage());
}
}
}
return result;
}
//get请求带参数、带请求头
public static String get(String urlWithParams, Map header) {
HttpGet httpget = new HttpGet(urlWithParams);
if (!MapUtils.isEmpty(header)) {
header.forEach(httpget::addHeader);
}
CloseableHttpClient httpClient = null;
String result;
try {
httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, CHARSET);
httpget.releaseConnection();
release(response, httpClient);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (Exception e) {
Log.error(e.getMessage());
}
}
}
return result;
}
public static String get(String urlWithParams) throws IOException {
return get(urlWithParams, null);
}
//发送post请求,带json请求体和请求头
public static ResponseEntity postJson(String url, String json, Map headersMap, Integer retryNum) {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(120000);
factory.setReadTimeout(120000);
RestTemplate restTemplate = new RestTemplate(factory);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
for (Map.Entry entry : headersMap.entrySet()) {
headers.add(entry.getKey(), entry.getValue());
}
org.springframework.http.HttpEntity request = new org.springframework.http.HttpEntity<>(json, headers);
ResponseEntity response = null;
try {
response = restTemplate.postForEntity(url, request, String.class);
if (retryNum > 0 && !HttpStatus.OK.equals(response.getStatusCode())) {
retryNum--;
postJson(url, json, headersMap, retryNum);
}
} catch (Exception e) {
if (retryNum > 0) {
retryNum--;
postJson(url, json, headersMap, retryNum);
} else {
throw e;
}
}
return response;
}
}
get方法调用:
public String callMesEqp() {
Map header = new HashMap<>();
ResponseEntity response;
HttpStatus statusCode;
String responseBody = "";
try {
responseBody = HttpClientUtil.get("http://192.168.220.220:9001/api/Interfaces/ApsSync/ApsSyncEqp", header);
} catch (Throwable e) {
}
return responseBody;
}
post方法调用:
public String callMesStepEqp(String syncTime) {
Map header = new HashMap<>();
ResponseEntity response = null;
HttpStatus statusCode;
String responseBody = "";
MesStepEqpQuery query = new MesStepEqpQuery();
//query就是请求参数,全是字符串
query.setTrxDate(syncTime);
String jsonString = JSON.toJSONString(query);
try {
response = HttpClientUtil.postJson("http://192.168.220.220:9001/api/Interfaces/ApsSync/GetStepEqpAreaInfo", jsonString, header, 1);
} catch (Throwable e) {
}
return response.getBody();
}
使用ResTemplate:
@Autowired
RestTemplate restTemplate;
@ApiOperation(value = "通过id获取用户", notes = "通过id获取用户")
@GetMapping("getUserByIdApi")
public Result getUserByIdApi(@ApiParam("用户id") Integer id) {
// UserVO vo = restTemplate.getForObject("http://127.0.0.1:8081/v1/user/getUserById?id=" + id, UserVO.class);
restTemplate.getForObject("http://127.0.0.1:8081/v1/user/getUserById?id=" + id, Result.class);
// return Result.success(vo);
return (restTemplate.getForObject("http://127.0.0.1:8081/v1/user/getUserById?id=" + id, Result.class));
}
使用springCloud的Eureka:
注意我的jdk和cloud版本:
4.0.0
org.cloud
springCloudPuls
1.0-SNAPSHOT
cloud-common
cloud-user
cloud-auth
cloud-eureka
pom
org.springframework.cloud
spring-cloud-dependencies
2022.0.3
pom
import
org.springframework.boot
spring-boot-dependencies
3.1.5
pom
import
mysql
mysql-connector-java
8.0.28
com.alibaba
druid
1.2.16
junit
junit
4.13.2
test
org.projectlombok
lombok
1.18.28
log4j
log4j
1.2.17
io.swagger
swagger-annotations
1.5.20
com.baomidou
mybatis-plus-boot-starter
3.5.3.1
cn.dev33
sa-token-spring-boot3-starter
1.37.0
编写Eureka服务器:
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
yml:
server:
port: 8084
#eureka配置
eureka:
instance:
hostname: locahost
client:
register-with-eureka: false
fetch-registry: false #is false,me is eurekaService,true is not
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka
springBoot启动类上加上:
@EnableEurekaServer
将服务注册进来:
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
4.1.0
yml:
server:
port: 8081
spring:
application:
name: cloude-user-server
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://192.168.126.128:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
username: root
password: 123456
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#eureka配置
# eureka
eureka:
client:
register-with-eureka: true #注册eureka
fetch-registry: true # 获取注册信息
service-url:
defaultZone: http://127.0.0.1:8084/eureka #访问地址,一定得是ip地址和端口号!!!
instance:
prefer-ip-address: true #暴露ip
instance-id: xry #名字
management:
endpoints:
web:
exposure:
include: '*'
jmx:
exposure:
include: '*'
info:
name: qx
启动类加上:
@EnableDiscoveryClient
然后访问Eureka的页面,http://localhost:8084/
未完,待续