| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234 |
- package com.mes.util;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import java.io.*;
- import java.net.HttpURLConnection;
- import java.net.URISyntaxException;
- import java.net.URL;
- import java.nio.charset.StandardCharsets;
- public class HttpUtils {
- public static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
- /**
- * HTTP请求,正确报文解析,并保存数据到生产记录数据
- * @return
- * @throws URISyntaxException
- */
- //http post请求
- public static String sendRequest(String urlParam) {
- String requestType = "POST";
- //根据接收内容返回数据结果
- String ret = "";
- log.info("http请求路径: {}", urlParam);
- HttpURLConnection con = null;
- BufferedReader buffer = null;
- StringBuffer resultBuffer = null;
- try {
- URL url = new URL(urlParam);
- //得到连接对象
- con = (HttpURLConnection) url.openConnection();
- //设置请求类型
- con.setRequestMethod(requestType);
- //设置请求需要返回的数据类型和字符集类型
- con.setRequestProperty("Content-Type", "application/json;charset=GBK");
- //允许写出
- con.setDoOutput(true);
- //允许读入
- con.setDoInput(true);
- //不使用缓存
- con.setUseCaches(false);
- //得到响应码
- int responseCode = con.getResponseCode();
- if(responseCode == HttpURLConnection.HTTP_OK){
- //得到响应流
- InputStream inputStream = con.getInputStream();
- //将响应流转换成字符串
- resultBuffer = new StringBuffer();
- String line;
- buffer = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
- while ((line = buffer.readLine()) != null) {
- resultBuffer.append(line);
- }
- log.info("http响应结果: {}", resultBuffer);
- ret = resultBuffer.toString();
- }else {
- //ret = String.valueOf(responseCode);
- ret = "false";
- }
- con.disconnect();
- }catch(Exception e) {
- ret = "false";
- }
- return ret;
- }
- public static String sendPostRequest(String urlParam, String params) {
- String requestType = "POST";
- //根据接收内容返回数据结果
- String ret = "";
- log.info("http请求路径: {}", urlParam);
- HttpURLConnection con = null;
- BufferedReader buffer = null;
- StringBuffer resultBuffer = null;
- try {
- URL url = new URL(urlParam);
- //得到连接对象
- con = (HttpURLConnection) url.openConnection();
- //设置请求类型
- con.setRequestMethod(requestType);
- //设置请求需要返回的数据类型和字符集类型
- con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=GBK");
- //允许写出
- con.setDoOutput(true);
- //允许读入
- con.setDoInput(true);
- //不使用缓存
- con.setUseCaches(false);
- // 获取URLConnection对象对应的输出流
- OutputStreamWriter out = new OutputStreamWriter( con.getOutputStream(),"UTF-8");// utf-8编码
- // 发送请求参数
- out.write(params);
- //得到响应码
- int responseCode = con.getResponseCode();
- if(responseCode == HttpURLConnection.HTTP_OK){
- //得到响应流
- InputStream inputStream = con.getInputStream();
- //将响应流转换成字符串
- resultBuffer = new StringBuffer();
- String line;
- buffer = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
- while ((line = buffer.readLine()) != null) {
- resultBuffer.append(line);
- }
- log.info("http响应结果: {}", resultBuffer);
- ret = resultBuffer.toString();
- }else {
- //ret = String.valueOf(responseCode);
- ret = "false";
- }
- con.disconnect();
- }catch(Exception e) {
- ret = "false";
- }
- return ret;
- }
- public static String sendPostRequestJson(String apiUrl, String jsonData) throws IOException {
- URL url = new URL(apiUrl);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("POST");
- conn.setRequestProperty("Content-Type", "application/json");
- conn.setDoOutput(true);
- // 发送请求数据
- try (OutputStream os = conn.getOutputStream()) {
- byte[] input = jsonData.getBytes("utf-8");
- os.write(input, 0, input.length);
- }
- // 获取响应数据
- StringBuilder response = new StringBuilder();
- int responseCode = conn.getResponseCode();
- // System.out.println("Sending POST request to URL: " + apiUrl);
- // System.out.println("Post parameters: " + jsonData);
- // System.out.println("Response Code: " + responseCode);
- try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
- String responseLine;
- while ((responseLine = br.readLine()) != null) {
- response.append(responseLine.trim());
- }
- }
- conn.disconnect();
- return response.toString();
- }
- /**
- * 发送 JSON 格式的 POST 请求
- *
- * @param urlString 目标 URL
- * @param jsonInput JSON 请求体
- * @param timeoutMs 连接和读取超时时间(毫秒)
- * @return 响应内容(JSON 字符串),失败时返回 null
- */
- public static String sendJsonPost(String urlString, String jsonInput, int timeoutMs) {
- HttpURLConnection conn = null;
- try {
- // 1. 创建连接
- URL url = new URL(urlString);
- conn = (HttpURLConnection) url.openConnection();
- // 2. 配置请求参数
- conn.setRequestMethod("POST");
- conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
- conn.setRequestProperty("Accept", "application/json");
- conn.setConnectTimeout(timeoutMs);
- conn.setReadTimeout(timeoutMs);
- conn.setDoOutput(true); // 允许写入请求体
- // 3. 发送 JSON 数据
- try (OutputStream os = conn.getOutputStream()) {
- byte[] input = jsonInput.getBytes(StandardCharsets.UTF_8);
- os.write(input, 0, input.length);
- }
- // 4. 处理响应
- int status = conn.getResponseCode();
- if (status >= 200 && status < 300) {
- // 读取成功响应流
- try (InputStream is = conn.getInputStream();
- BufferedReader br = new BufferedReader(
- new InputStreamReader(is, StandardCharsets.UTF_8))) {
- StringBuilder response = new StringBuilder();
- String line;
- while ((line = br.readLine()) != null) {
- response.append(line);
- }
- return response.toString();
- }
- } else {
- // 读取错误流(部分服务器将错误信息放在错误流中)
- try (InputStream es = conn.getErrorStream();
- BufferedReader br = new BufferedReader(
- new InputStreamReader(es, StandardCharsets.UTF_8))) {
- StringBuilder errorResponse = new StringBuilder();
- String line;
- while ((line = br.readLine()) != null) {
- errorResponse.append(line);
- }
- log.error("HTTP Error {}: {}", status, errorResponse.toString());
- }
- return null;
- }
- } catch (Exception e) {
- log.error("http请求失败", e);
- return null;
- } finally {
- if (conn != null) {
- conn.disconnect(); // 关闭连接
- }
- }
- }
- /**
- * 发送 JSON 格式的 POST 请求
- *
- * @param urlString 目标 URL
- * @param jsonInput JSON 请求体
- * @return 响应内容(JSON 字符串),失败时返回 null
- */
- public static String sendJsonPost(String urlString, String jsonInput) {
- return sendJsonPost(urlString, jsonInput, 5000);
- }
-
- }
|