寄点电站数据接入
This commit is contained in:
@ -0,0 +1,177 @@
|
||||
package com.ho.business.service;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.ho.business.vo.req.StationReqVO;
|
||||
import com.ho.common.tools.constant.CommonConstant;
|
||||
import com.ho.common.tools.service.RedisService;
|
||||
import com.ho.common.tools.util.HttpUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 西安寄点能源股份有限公司
|
||||
* 西安寄点能源 API 接口 服务
|
||||
*
|
||||
* @author kerwin
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
public class ShipEnergyService {
|
||||
|
||||
/**
|
||||
* token 缓存 key
|
||||
*/
|
||||
private static final String SHIP_ENERGY_TOKEN_KEY = "ShipEnergyToken";
|
||||
|
||||
/**
|
||||
* 获取token 参数 platform
|
||||
*/
|
||||
private static final String PLATFORM = "f9599b6c79a5efbfc6ddce5fed1bbed5";
|
||||
|
||||
/**
|
||||
* 获取token 参数 platformsecret
|
||||
*/
|
||||
private static final String PLATFORM_SECRET = "2928b16f9cb8e85199a4caa6ba3b6620";
|
||||
|
||||
/**
|
||||
* 寄点能源- 获取token Url
|
||||
*/
|
||||
private static final String TOKEN_URL = "https://www.emind2000.cloud/rest-api/gettoken";
|
||||
|
||||
/**
|
||||
* 寄点能源- 获取项目列表 Url
|
||||
*/
|
||||
private static final String STATION_URL = "https://www.emind2000.cloud/rest-api/getStations";
|
||||
|
||||
/**
|
||||
* 寄点能源- 主监控汇总 Url
|
||||
*/
|
||||
private static final String MAIN_URL = "https://www.emind2000.cloud/rest-api/getMainTotal";
|
||||
|
||||
@Autowired
|
||||
private RedisService redisService;
|
||||
|
||||
@Autowired
|
||||
private StationService stationService;
|
||||
|
||||
/**
|
||||
* 寄点能源 - 获取token
|
||||
* @return token
|
||||
*/
|
||||
public String getToken(){
|
||||
String token = null;
|
||||
if(redisService.hasKey(SHIP_ENERGY_TOKEN_KEY)){
|
||||
token = (String)redisService.get(SHIP_ENERGY_TOKEN_KEY);
|
||||
}
|
||||
Map<String, String> params = Maps.newHashMap();
|
||||
params.put("platform",PLATFORM);
|
||||
params.put("platformsecret",PLATFORM_SECRET);
|
||||
try {
|
||||
String json = HttpUtils.getWithForm(TOKEN_URL,params);
|
||||
JSONObject jsonObject = JSONObject.parseObject(json);
|
||||
Integer code = jsonObject.getInteger("code");
|
||||
if(CommonConstant.HttpCode.SUCCESS_CODE.equals(code)){
|
||||
JSONObject data = jsonObject.getJSONObject("data");
|
||||
token = data.getString("access_token");
|
||||
//redis 缓存
|
||||
redisService.set(SHIP_ENERGY_TOKEN_KEY,token,10, TimeUnit.HOURS);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 寄点能源 - 获取 项目列表
|
||||
* @return 项目列表 json 字符串
|
||||
*/
|
||||
public String getStations(){
|
||||
String Authorization = "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjo5Nzg2LCJ1c2VyX2tleSI6Ijk3ODY6N2RkNjU0MTgtNDg5ZS00MzgzLWI1ZmYtMTU2MmI5ZTY0NDFkIiwidXNlcm5hbWUiOiJ6emt5YXBpIn0.fQLMlOHaEjmfHeyEu5EcxZmQ8UjRBOUoteNV-tJ2ttAwyJmQidOk7xqL25K_wRIC-OQKt0vFVOpTzMFdH71uhw";
|
||||
Map<String, String> headers = new HashMap<>();
|
||||
headers.put("Authorization",Authorization);
|
||||
try {
|
||||
String json = HttpUtils.getWithHeaders(STATION_URL,null,headers);
|
||||
JSONObject jsonObject = JSONObject.parseObject(json);
|
||||
Integer code = jsonObject.getInteger("code");
|
||||
if(CommonConstant.HttpCode.SUCCESS_CODE.equals(code)){
|
||||
JSONObject data = jsonObject.getJSONObject("data");
|
||||
return data.getString("rows");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 寄点能源 - 获取 主监控汇总信息
|
||||
* @param stationId 电站id
|
||||
* @return 返回对应电站汇总信息
|
||||
*/
|
||||
public String getMainTotal(String stationId){
|
||||
String Authorization = "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjo5Nzg2LCJ1c2VyX2tleSI6Ijk3ODY6MmE5YjUzODUtNjNiNC00OWRiLWFjODEtNzhmNWRmNjE0ZDgyIiwidXNlcm5hbWUiOiJ6emt5YXBpIn0.WMi4PgYQByeYXBfOGVM0mc4P5GcyAcGRkDo8F7TK8fXIkj9QZ9D34WmugiVX3GxRGODFs3u1ujH7qJyuQAM99w";
|
||||
Map<String, String> headers = new HashMap<>();
|
||||
headers.put("Authorization",Authorization);
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("stationId",stationId);
|
||||
try {
|
||||
String json = HttpUtils.getWithHeaders(MAIN_URL,params,headers);
|
||||
JSONObject jsonObject = JSONObject.parseObject(json);
|
||||
Integer code = jsonObject.getInteger("code");
|
||||
if(CommonConstant.HttpCode.SUCCESS_CODE.equals(code)){
|
||||
return jsonObject.getString("data");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/*****************************************业务处理******************************************************/
|
||||
|
||||
/**
|
||||
* 寄点能源 - 电站信息融合储能平台处理
|
||||
*/
|
||||
public void addShipEnergyStation(){
|
||||
String stationJson = getStations();
|
||||
JSONArray jsonStation = JSON.parseArray(stationJson);
|
||||
jsonStation.forEach(i->{
|
||||
JSONObject jsonObj = (JSONObject) i;
|
||||
Integer stationId = jsonObj.getInteger("stationId");
|
||||
String name = jsonObj.getString("name");
|
||||
String address = jsonObj.getString("address");
|
||||
String province = jsonObj.getString("province");
|
||||
String city = jsonObj.getString("city");
|
||||
BigDecimal longitude = jsonObj.getBigDecimal("longitude");
|
||||
BigDecimal latitude = jsonObj.getBigDecimal("latitude");
|
||||
BigDecimal maxPower = jsonObj.getBigDecimal("maxPower");
|
||||
BigDecimal capacity = jsonObj.getBigDecimal("capacity");
|
||||
Date commossioningTime = jsonObj.getDate("commossioningTime");
|
||||
StationReqVO vo = new StationReqVO();
|
||||
vo.setId(stationId+10000);
|
||||
vo.setName(name);
|
||||
vo.setAddress(address);
|
||||
vo.setLongitude(longitude);
|
||||
vo.setLatitude(latitude);
|
||||
vo.setCapacity(capacity);
|
||||
vo.setRatePower(maxPower);
|
||||
vo.setGridTime(commossioningTime);
|
||||
vo.setGroupId(155);
|
||||
vo.setDeptId(155);
|
||||
stationService.insertStation(vo);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,32 @@
|
||||
package com.ho.business.controller;
|
||||
|
||||
import com.ho.business.service.ShipEnergyService;
|
||||
import com.ho.common.tools.annotation.TokenIgnore;
|
||||
import com.ho.common.tools.constant.ContextConstant;
|
||||
import com.ho.common.tools.exception.DataResult;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RequestMapping(ContextConstant.BUSINESS + "shipEnergyStation")
|
||||
@RestController
|
||||
@Api(tags = "业务模块-寄点能源电站管理")
|
||||
public class ShipEnergyController {
|
||||
|
||||
|
||||
@Autowired
|
||||
ShipEnergyService shipEnergyService;
|
||||
|
||||
|
||||
@PostMapping("add")
|
||||
@ApiOperation(value = "新增电站接口")
|
||||
@TokenIgnore
|
||||
public DataResult add() {
|
||||
shipEnergyService.addShipEnergyStation();
|
||||
return DataResult.success();
|
||||
}
|
||||
|
||||
}
|
||||
@ -994,4 +994,9 @@ public interface CommonConstant {
|
||||
String CF_FROZEN = "cfFrozen";
|
||||
//将数据库统配符合“_”变成普通字符
|
||||
String JOIN_STATION_ID = "\\_";
|
||||
|
||||
interface HttpCode {
|
||||
// 调用成功code
|
||||
Integer SUCCESS_CODE = 200;
|
||||
}
|
||||
}
|
||||
|
||||
@ -35,7 +35,7 @@ public class AddressUntils {
|
||||
}
|
||||
|
||||
public static JSONObject getLocationInfo(String lat, String lng) throws IOException {
|
||||
String urlString = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + lat + "," + lng + "&key=" + secretKey;
|
||||
String urlString = "http://apis.map.qq.com/ws/geocoder/v1/?location=" + lat + "," + lng + "&key=" + secretKey;
|
||||
System.out.println("请求经纬度url:" + urlString);
|
||||
URL url = new URL(urlString);
|
||||
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
|
||||
|
||||
@ -0,0 +1,342 @@
|
||||
package com.ho.common.tools.util;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.StringJoiner;
|
||||
|
||||
/**
|
||||
* HTTP工具类 - 支持GET/POST请求,支持表单和JSON传参
|
||||
*/
|
||||
public class HttpUtils {
|
||||
/**
|
||||
* 连接超时时间(毫秒)
|
||||
*/
|
||||
private static final int CONNECT_TIMEOUT = 10000;
|
||||
|
||||
/**
|
||||
* 读取超时时间(毫秒)
|
||||
*/
|
||||
private static final int READ_TIMEOUT = 30000;
|
||||
|
||||
/**
|
||||
* 发送GET请求(表单参数模式)
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @param params 表单参数
|
||||
* @return 响应字符串
|
||||
* @throws IOException 网络异常
|
||||
*/
|
||||
public static String getWithForm(String url, Map<String, String> params) throws IOException {
|
||||
return get(url, buildFormParams(params), "application/x-www-form-urlencoded");
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送GET请求(JSON参数模式)
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @param jsonParams JSON参数字符串
|
||||
* @return 响应字符串
|
||||
* @throws IOException 网络异常
|
||||
*/
|
||||
public static String getWithJson(String url, String jsonParams) throws IOException {
|
||||
// 注意:GET请求通常不支持请求体中的JSON参数
|
||||
// 但某些API可能支持,这里将其作为查询参数传递
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("json", jsonParams);
|
||||
return get(url, buildFormParams(params), "application/x-www-form-urlencoded");
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送POST请求(表单参数模式)
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @param params 表单参数
|
||||
* @return 响应字符串
|
||||
* @throws IOException 网络异常
|
||||
*/
|
||||
public static String postWithForm(String url, Map<String, String> params) throws IOException {
|
||||
return post(url, buildFormParams(params), "application/x-www-form-urlencoded");
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送POST请求(JSON参数模式)
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @param jsonParams JSON参数字符串
|
||||
* @return 响应字符串
|
||||
* @throws IOException 网络异常
|
||||
*/
|
||||
public static String postWithJson(String url, String jsonParams) throws IOException {
|
||||
return post(url, jsonParams, "application/json; charset=utf-8");
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送POST请求(JSON参数模式,使用Map自动转换为JSON)
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @param params 参数Map
|
||||
* @return 响应字符串
|
||||
* @throws IOException 网络异常
|
||||
*/
|
||||
public static String postWithJson(String url, Map<String, Object> params) throws IOException {
|
||||
String jsonParams = mapToJson(params);
|
||||
return postWithJson(url, jsonParams);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送GET请求(基础方法)
|
||||
*/
|
||||
private static String get(String url, String queryParams, String contentType) throws IOException {
|
||||
String fullUrl = url;
|
||||
if (queryParams != null && !queryParams.isEmpty()) {
|
||||
fullUrl = url + "?" + queryParams;
|
||||
}
|
||||
|
||||
HttpURLConnection connection = null;
|
||||
BufferedReader reader = null;
|
||||
|
||||
try {
|
||||
URL requestUrl = new URL(fullUrl);
|
||||
connection = (HttpURLConnection) requestUrl.openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
connection.setConnectTimeout(CONNECT_TIMEOUT);
|
||||
connection.setReadTimeout(READ_TIMEOUT);
|
||||
connection.setRequestProperty("Content-Type", contentType);
|
||||
connection.setRequestProperty("User-Agent", "HttpUtils/1.0");
|
||||
|
||||
int responseCode = connection.getResponseCode();
|
||||
if (responseCode == HttpURLConnection.HTTP_OK) {
|
||||
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
|
||||
return readResponse(reader);
|
||||
} else {
|
||||
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8));
|
||||
String errorResponse = readResponse(reader);
|
||||
throw new IOException("HTTP GET Request Failed with Error Code: " + responseCode + ", Response: " + errorResponse);
|
||||
}
|
||||
} finally {
|
||||
reader.close();
|
||||
connection.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送POST请求(基础方法)
|
||||
*/
|
||||
private static String post(String url, String requestBody, String contentType) throws IOException {
|
||||
HttpURLConnection connection = null;
|
||||
OutputStream outputStream = null;
|
||||
BufferedReader reader = null;
|
||||
|
||||
try {
|
||||
URL requestUrl = new URL(url);
|
||||
connection = (HttpURLConnection) requestUrl.openConnection();
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setConnectTimeout(CONNECT_TIMEOUT);
|
||||
connection.setReadTimeout(READ_TIMEOUT);
|
||||
connection.setDoOutput(true);
|
||||
connection.setRequestProperty("Content-Type", contentType);
|
||||
connection.setRequestProperty("User-Agent", "HttpUtils/1.0");
|
||||
connection.setRequestProperty("Accept", "application/json, text/plain, */*");
|
||||
|
||||
// 写入请求体
|
||||
if (requestBody != null && !requestBody.isEmpty()) {
|
||||
outputStream = connection.getOutputStream();
|
||||
outputStream.write(requestBody.getBytes(StandardCharsets.UTF_8));
|
||||
outputStream.flush();
|
||||
}
|
||||
|
||||
int responseCode = connection.getResponseCode();
|
||||
if (responseCode == HttpURLConnection.HTTP_OK ||
|
||||
responseCode == HttpURLConnection.HTTP_CREATED ||
|
||||
responseCode == HttpURLConnection.HTTP_ACCEPTED) {
|
||||
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
|
||||
return readResponse(reader);
|
||||
} else {
|
||||
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8));
|
||||
String errorResponse = readResponse(reader);
|
||||
throw new IOException("HTTP POST Request Failed with Error Code: " + responseCode + ", Response: " + errorResponse);
|
||||
}
|
||||
} finally {
|
||||
outputStream.close();
|
||||
reader.close();
|
||||
connection.connect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建表单参数字符串
|
||||
*/
|
||||
private static String buildFormParams(Map<String, String> params) throws UnsupportedEncodingException {
|
||||
if (params == null || params.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
StringJoiner joiner = new StringJoiner("&");
|
||||
for (Map.Entry<String, String> entry : params.entrySet()) {
|
||||
String encodedKey = URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.toString());
|
||||
String encodedValue = URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString());
|
||||
joiner.add(encodedKey + "=" + encodedValue);
|
||||
}
|
||||
return joiner.toString();
|
||||
}
|
||||
/**
|
||||
* 将Map转换为JSON字符串(简单实现,实际项目中建议使用Jackson/Gson等库)
|
||||
*/
|
||||
private static String mapToJson(Map<String, Object> params) {
|
||||
if (params == null || params.isEmpty()) {
|
||||
return "{}";
|
||||
}
|
||||
|
||||
StringBuilder jsonBuilder = new StringBuilder("{");
|
||||
boolean first = true;
|
||||
|
||||
for (Map.Entry<String, Object> entry : params.entrySet()) {
|
||||
if (!first) {
|
||||
jsonBuilder.append(",");
|
||||
}
|
||||
first = false;
|
||||
|
||||
jsonBuilder.append("\"").append(escapeJson(entry.getKey())).append("\":");
|
||||
|
||||
Object value = entry.getValue();
|
||||
if (value == null) {
|
||||
jsonBuilder.append("null");
|
||||
} else if (value instanceof String) {
|
||||
jsonBuilder.append("\"").append(escapeJson((String) value)).append("\"");
|
||||
} else if (value instanceof Number || value instanceof Boolean) {
|
||||
jsonBuilder.append(value);
|
||||
} else {
|
||||
// 复杂对象需要序列化,这里简单处理
|
||||
jsonBuilder.append("\"").append(escapeJson(value.toString())).append("\"");
|
||||
}
|
||||
}
|
||||
|
||||
jsonBuilder.append("}");
|
||||
return jsonBuilder.toString();
|
||||
}
|
||||
/**
|
||||
* 转义JSON特殊字符
|
||||
*/
|
||||
private static String escapeJson(String input) {
|
||||
if (input == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return input.replace("\\", "\\\\")
|
||||
.replace("\"", "\\\"")
|
||||
.replace("\b", "\\b")
|
||||
.replace("\f", "\\f")
|
||||
.replace("\n", "\\n")
|
||||
.replace("\r", "\\r")
|
||||
.replace("\t", "\\t");
|
||||
}
|
||||
/**
|
||||
* 读取响应内容
|
||||
*/
|
||||
private static String readResponse(BufferedReader reader) throws IOException {
|
||||
StringBuilder response = new StringBuilder();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
response.append(line);
|
||||
}
|
||||
return response.toString();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 发送带请求头的GET请求(扩展方法)
|
||||
*/
|
||||
public static String getWithHeaders(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
|
||||
String fullUrl = url;
|
||||
if (params != null && !params.isEmpty()) {
|
||||
fullUrl = url + "?" + buildFormParams(params);
|
||||
}
|
||||
|
||||
HttpURLConnection connection = null;
|
||||
BufferedReader reader = null;
|
||||
|
||||
try {
|
||||
URL requestUrl = new URL(fullUrl);
|
||||
connection = (HttpURLConnection) requestUrl.openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
connection.setConnectTimeout(CONNECT_TIMEOUT);
|
||||
connection.setReadTimeout(READ_TIMEOUT);
|
||||
connection.setRequestProperty("User-Agent", "HttpUtils/1.0");
|
||||
|
||||
// 添加自定义请求头
|
||||
if (headers != null) {
|
||||
for (Map.Entry<String, String> header : headers.entrySet()) {
|
||||
connection.setRequestProperty(header.getKey(), header.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
int responseCode = connection.getResponseCode();
|
||||
if (responseCode == HttpURLConnection.HTTP_OK) {
|
||||
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
|
||||
return readResponse(reader);
|
||||
} else {
|
||||
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8));
|
||||
String errorResponse = readResponse(reader);
|
||||
throw new IOException("HTTP GET Request Failed with Error Code: " + responseCode + ", Response: " + errorResponse);
|
||||
}
|
||||
} finally {
|
||||
reader.close();
|
||||
connection.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送带请求头的POST请求(扩展方法)
|
||||
*/
|
||||
public static String postWithHeaders(String url, String requestBody, String contentType, Map<String, String> headers) throws IOException {
|
||||
HttpURLConnection connection = null;
|
||||
OutputStream outputStream = null;
|
||||
BufferedReader reader = null;
|
||||
|
||||
try {
|
||||
URL requestUrl = new URL(url);
|
||||
connection = (HttpURLConnection) requestUrl.openConnection();
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setConnectTimeout(CONNECT_TIMEOUT);
|
||||
connection.setReadTimeout(READ_TIMEOUT);
|
||||
connection.setDoOutput(true);
|
||||
connection.setRequestProperty("Content-Type", contentType);
|
||||
connection.setRequestProperty("User-Agent", "HttpUtils/1.0");
|
||||
|
||||
// 添加自定义请求头
|
||||
if (headers != null) {
|
||||
for (Map.Entry<String, String> header : headers.entrySet()) {
|
||||
connection.setRequestProperty(header.getKey(), header.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
// 写入请求体
|
||||
if (requestBody != null && !requestBody.isEmpty()) {
|
||||
outputStream = connection.getOutputStream();
|
||||
outputStream.write(requestBody.getBytes(StandardCharsets.UTF_8));
|
||||
outputStream.flush();
|
||||
}
|
||||
|
||||
int responseCode = connection.getResponseCode();
|
||||
if (responseCode == HttpURLConnection.HTTP_OK ||
|
||||
responseCode == HttpURLConnection.HTTP_CREATED ||
|
||||
responseCode == HttpURLConnection.HTTP_ACCEPTED) {
|
||||
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
|
||||
return readResponse(reader);
|
||||
} else {
|
||||
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8));
|
||||
String errorResponse = readResponse(reader);
|
||||
throw new IOException("HTTP POST Request Failed with Error Code: " + responseCode + ", Response: " + errorResponse);
|
||||
}
|
||||
} finally {
|
||||
outputStream.close();
|
||||
reader.close();
|
||||
connection.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user