在Java中调用Python接口可以通过以下几种方法:
1. 使用Java的`ProcessBuilder`类执行Python脚本:
ProcessBuilder processBuilder = new ProcessBuilder("python", "path/to/your/python_script.py");
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("Exit Code: " + exitCode);
2. 使用Jython库:
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class JavaCallPython {
public static void main(String[] args) {
try (PythonInterpreter interpreter = new PythonInterpreter()) {
interpreter.execfile("path/to/your/python_script.py");
PyObject result = interpreter.get("function_name");
// 调用Python函数
PyObject resultObj = result.__call__(args);
System.out.println(resultObj);
}
}
}
3. 使用`Runtime.getRuntime()`执行Python脚本:
try {
Process process = Runtime.getRuntime().exec("python path/to/your/python_script.py");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("Exit Code: " + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
4. 使用Flask创建Python Web接口:
Python Flask接口示例
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/getStr', methods=['POST', 'GET'])
def getStr():
return 'hello, world'
@app.route('/success/')
def success(name):
return 'welcome %s' % name
@app.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'POST':
user = request.form['nm']
print(user)
return 'logged in'
然后,在Java中通过HTTP请求调用这些接口:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:5000/getStr");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
请根据你的具体需求选择合适的方法。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/144691.html