欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 文化 > java 调用python接口方法

java 调用python接口方法

2025/11/10 16:07:48 来源:https://blog.csdn.net/geyaogang/article/details/148538036  浏览:    关键词:java 调用python接口方法

适用场景:对于http协议的外部python接口,业务系统前端不能直接调http 接口 先需要在业务系统java后端中写一个接口调用python接口作为中转

package com.example.ws.restful.technology;import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.sunshine.common.utils.LogUtil;
import com.sunshine.common.utils.webservice.BaseResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;import java.util.List;/*** @description: Web Service for processing external service requests* @date 2025年06月08日 下午1:20:42*/
@Path("/service")
public class ExternalServiceWebService {// 外部服务URL(通过配置文件或环境变量获取)private static final String EXTERNAL_SERVICE_URL = "http://example.com/service/";/*** @description: 初始化,调用外部服务* @param jsonStr 输入JSON字符串* @return JSON响应字符串*/@POST@Path("/")@Produces("application/json;charset=utf-8")@Consumes("application/json;charset=utf-8")public String init(String jsonStr) {Gson gson = new Gson();// 返回信息ExternalServiceResponse response = new ExternalServiceResponse();try {// 解析输入JSONExternalServiceRequest request = gson.fromJson(jsonStr, ExternalServiceRequest.class);// 获取数据List<Double> data = request.getData();Double param1 = request.getParam1();Double param2 = request.getParam2();// 构造外部服务请求体JsonObject requestBody = new JsonObject();requestBody.add("data", gson.toJsonTree(data));requestBody.addProperty("param1", param1);requestBody.addProperty("param2", param2);// 调用外部服务try (CloseableHttpClient httpClient = HttpClients.createDefault()) {HttpPost httpPost = new HttpPost(EXTERNAL_SERVICE_URL);httpPost.setHeader("Content-Type", "application/json;charset=utf-8");StringEntity entity = new StringEntity(gson.toJson(requestBody), "UTF-8");httpPost.setEntity(entity);try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {int statusCode = httpResponse.getStatusLine().getStatusCode();if (statusCode == 200) {String responseBody = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");JsonObject externalResponse = gson.fromJson(responseBody, JsonObject.class);// 设置响应数据response.setCode(externalResponse.get("code").getAsInt());response.setData(externalResponse.get("data").getAsString());} else {response.setCode(500);response.setMessage("Failed to call external service, status code: " + statusCode);}}} catch (Exception e) {response.setCode(500);response.setMessage("Error calling external service: " + e.getMessage());}} catch (Exception e) {// 异常处理,WS不抛出异常,通过响应对象进行处理response.setCode(500);response.setMessage("Error processing request: " + e.getMessage());} return gson.toJson(response);}}
/*** 请求类*/
class ExternalServiceRequest {private List<Double> data;private Double param1;private Double param2;public List<Double> getData() {return data;}public void setData(List<Double> data) {this.data = data;}public Double getParam1() {return param1;}public void setParam1(Double param1) {this.param1 = param1;}public Double getParam2() {return param2;}public void setParam2(Double param2) {this.param2 = param2;}
}
/*** 响应类*/
class ExternalServiceResponse extends BaseResponse {private String data;public String getData() {return data;}public void setData(String data) {this.data = data;}
}

说明

  1. HTTP客户端:使用org.apache.http.client(Apache HttpClient)来调用Python服务,确保能够正确发送POST请求并处理响应。
  2. 请求构造:将输入的data、getParam1和getParam2封装为JSON对象,发送到Python服务。
  3. 响应处理:解析Python服务的响应,提取code和data字段,设置到ExternalServiceResponse对象中。
  4. 异常处理:增加了对HTTP调用异常的处理,确保接口健壮性。
  5. 依赖:确保项目中包含org.apache.httpcomponents:httpclient依赖。如果未包含,可在Maven的pom.xml中添加:
    <dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.13</version>
    </dependency>
  6. 响应类:ExternalServiceResponse继承BaseResponse,并添加data字段以匹配输出格式。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词