1、添加依赖
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.9.1</version> </dependency>
2、service
/*调用python服务*/ @Override @Transactional(rollbackFor = Exception.class) public String callPythonService(String target) throws IOException { String url = "http://192.168.137.138:5555/targetrecommendation"; //MediaType指定请求体跟格式 MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); JSONObject jsonObject = new JSONObject(); jsonObject.put("target", target); RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString()); Request request = new Request.Builder()//创建一个 Request.Builder 对象,用于构建一个请求对象。 .url(url) .post(requestBody) .build();//构建一个新的 Request 对象并返回 Response response = client.newCall(request).execute();//execute() 获取服务端响应。 if (response.isSuccessful()) { String responseData = response.body().string();//获取服务端返回的数据,并将其转换为字符串类型 return responseData; } else { throw new IOException("Unexpected HTTP code " + response); } }
3、controller
public String requestPythonService(@RequestBody Map<String, Object> map) { String target = (String) map.get("target"); try { String result = scientifiObjectiveService.callPythonService(target); return result; } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } }