package com.example.demo.service;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import com.google.gson.Gson;
public class PythonProt {
public String knnRegressor(Float[][] array,String Address) {
try {
// 构建要发送的二维数组
// 使用 Gson 将二维数组转换为 JSON 字符串
Gson gson = new Gson();
String json = gson.toJson(array);
// 设置 URL
URL url = new URL(Address);
// 创建 HttpURLConnection 对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("POST");
// 设置请求头
connection.setRequestProperty("Content-Type", "application/json");
// 启用输出流,以便我们可以发送数据
connection.setDoOutput(true);
// 获取输出流并写入 JSON 数据
OutputStream os = connection.getOutputStream();
os.write(json.getBytes());
os.flush();
os.close();
// 发送请求并获取响应状态码
int responseCode = connection.getResponseCode();
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应内容
return response.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String NeuralNetwork(List<int[]> array, String Address) {
try {
// 构建要发送的二维数组
// 使用 Gson 将二维数组转换为 JSON 字符串
Gson gson = new Gson();
String json = gson.toJson(array);
// 设置 URL
URL url = new URL(Address);
// 创建 HttpURLConnection 对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("POST");
// 设置请求头
connection.setRequestProperty("Content-Type", "application/json");
// 启用输出流,以便我们可以发送数据
connection.setDoOutput(true);
// 获取输出流并写入 JSON 数据
OutputStream os = connection.getOutputStream();
os.write(json.getBytes());
os.flush();
os.close();
// 发送请求并获取响应状态码
int responseCode = connection.getResponseCode();
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应内容
return response.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
javaSpring与Python的flask框架实现通讯
最新推荐文章于 2024-08-19 14:41:29 发布