• Python提供API给JAVA调用,实现Python和Java之间的交互


    一、Java 调用Python 提供的API接口,有多种方法,本文通过Python 提供的Rest API进行调用

    二、在Python中创建一个REST API,你可以使用许多框架,其中两个最流行的框架是Flask和Django REST framework。这两个框架都提供了创建RESTful服务的强大功能

    三、代码

    案例: 通过url带参数传递

    1、Python (Rest API)
    这里需要提前安装flask库。

    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包:

         <dependency>
                 <groupId>com.squareup.okhttp3</groupId>
                 <artifactId>okhttp</artifactId>
                <version>4.9.1</version>
            </dependency>
    

    Java代码如下:

    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();
            }
        }
    }
    
  • 相关阅读:
    【SHELL】贪吃蛇
    Upper and lower bounds
    Kubernetes 集群 troubleshooting
    Vue3和码上掘金实现猜数字小游戏
    SpringMVC入门宝典(五)SpringMVC注解(下)
    C++游戏引擎Easy2D教程(1) —— 第一个程序
    Java底层自学大纲_JVM篇
    网络传输中的编码与解码
    开发那些事儿:如何利用Go单例模式保障流媒体高并发的安全性?
    AOP简单使用模版
  • 原文地址:https://blog.csdn.net/qq_42393720/article/details/140053233