一、Java 调用Python 提供的API接口,有多种方法,本文通过Python 提供的Rest API进行调用
二、在Python中创建一个REST API,你可以使用许多框架,其中两个最流行的框架是Flask和Django REST framework。这两个框架都提供了创建RESTful服务的强大功能
三、代码
案例: 通过url带参数传递
1、Python (Rest API)
这里需要提前安装flask库。
bash
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/hello', methods=['GET'])
def process_data():
param = request.args.get('param')
result = "Hello "+param+"!"
return jsonify({'result': result})
if __name__ == '__main__':
app.run(debug=True)
2、Java代码
Java 是Maven项目,需要在pom.xml中导入okhttp包:
bash
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
Java代码如下:
bash
import okhttp3.*;
import java.io.IOException;
public class JavaClient {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String get(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
public static void main(String[] args) {
JavaClient client = new JavaClient();
String response = null;
try {
response = client.get("http://localhost:5000/hello?param=jieke");
System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
}
}
}