将Java与Python Flask连接 [英] Connect Java with Python Flask

查看:56
本文介绍了将Java与Python Flask连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Flask API:

I have a simple Flask API:

from flask import Flask, jsonify

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello World!'

@app.route('/add/<params>', methods = ['GET'])
def add_numbers(params):
    #params is expected to be a dictionary: {'x': 1, 'y':2}
    params = eval(params)
    return jsonify({'sum': params['x'] + params['y']})

if __name__ == '__main__':
    app.run(debug=True)

现在,我想从Java调用此方法并提取结果.我尝试使用 java.net.URL java.net.HttpURLConnection;

Now, I want to call this method from Java and extract the result. I have tried using java.net.URL and java.net.HttpURLConnection;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class MyClass {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://127.0.0.1:5000/add/{'x':100, 'y':1}");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }

            conn.disconnect();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e){
e.printStackTrace();
        }
    }
}

但是它不起作用.在烧瓶服务器中,我收到一条错误消息:

But it doesn't work. In the flask server I get an error message:

代码400,消息错误的请求语法("GET/add/{'x':100,'y':1} HTTP/1.1)

code 400, message Bad request syntax ("GET /add/{'x':100, 'y':1} HTTP/1.1")

"GET/add/{'x':100,'y':1} HTTP/1.1" HTTPStatus.BAD_REQUEST-

"GET /add/{'x':100, 'y':1} HTTP/1.1" HTTPStatus.BAD_REQUEST -

在Java代码中,我得到了错误:

and in Java code, I get the error:

线程"main"中的异常java.lang.RuntimeException:失败:HTTP错误代码:-1在MyClass.main(MyClass.java:17)

Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : -1 at MyClass.main(MyClass.java:17)

我做错了什么?

我的最终目标是将字典对象传递给我的python函数,并将函数的响应返回给java.该词典可以包含超过一千个单词的文本值.我该如何实现?

My final aim is to pass dictionary objects to my python function and return the response of the function to java. The dictionary can contain text values of over thousand words. How can I achieve this?

修改

根据评论和答案,我更新了我的Flask代码,以避免使用eval并进行更好的设计:

Based on the comments and the answers, I have updated my Flask code to avoid using eval and for better design:

@app.route('/add/', methods = ['GET'])
def add_numbers():
    params = {'x': int(request.args['x']), 'y': int(request.args['y']), 'text': request.args['text']}
    print(params['text'])
    return jsonify({'sum': params['x'] + params['y']})

现在我的网址是:"http://127.0.0.1:5000/add?x=100&y=12&text='Test'"

这样好吗?

推荐答案

从上述@TallChuck的评论开始,您需要替换或删除URL中的空格

As from @TallChuck's comment above, you need to replace or remove spaces in the URL

URL url = new URL("http://127.0.0.1:5000/add?x=100&y=12&text='Test'");

我建议利用请求对象来检索GET调用中的参数.

I would suggest to make use of a request object to retrieve parameters in your GET call.

请求对象

要访问Flask中的传入数据,您必须使用请求目的.请求对象保存来自请求的所有传入数据,其中包括mimetype,引荐来源网址,IP地址,原始数据,HTTP方法和标头,等等.虽然所有信息请求对象持有可能很有用,我们只关注数据通常是由我们的端点的调用者直接提供的.

The Request Object

To access the incoming data in Flask, you have to use the request object. The request object holds all incoming data from the request, which includes the mimetype, referrer, IP address, raw data, HTTP method, and headers, among other things. Although all the information the request object holds can be useful we'll only focus on the data that is normally directly supplied by the caller of our endpoint.

如评论中提到的,用于发布大量参数和数据,对此任务更合适的实现可能是使用POST方法.

As mentioned in the comments to post large amounts of paramters and data, A more appropriate implementation for this task would be probably using the POST method.

这是一个有关后端中POST的相同实现的示例:

Here's an example about the same implementation for POST in the backend:

from flask import Flask, jsonify, request
import json

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

@app.route('/add/', methods = ['POST'])
def add_numbers():
    if request.method == 'POST':
        decoded_data = request.data.decode('utf-8')
        params = json.loads(decoded_data)
        return jsonify({'sum': params['x'] + params['y']})

if __name__ == '__main__':
    app.run(debug=True)

这是使用cURL测试POST后端的简单方法:

Here's a simple way to test the POST backend using cURL:

 curl -d '{"x":5, "y":10}' -H "Content-Type: application/json" -X POST http://localhost:5000/add

使用Java发布请求:

Using Java to post the request:

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class PostClass {
    public static void main(String args[]){
        HttpURLConnection conn = null;
        DataOutputStream os = null;
        try{
            URL url = new URL("http://127.0.0.1:5000/add/"); //important to add the trailing slash after add
            String[] inputData = {"{\"x\": 5, \"y\": 8, \"text\":\"random text\"}",
                    "{\"x\":5, \"y\":14, \"text\":\"testing\"}"};
            for(String input: inputData){
                byte[] postData = input.getBytes(StandardCharsets.UTF_8);
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty( "charset", "utf-8");
                conn.setRequestProperty("Content-Length", Integer.toString(input.length()));
                os = new DataOutputStream(conn.getOutputStream());
                os.write(postData);
                os.flush();

                if (conn.getResponseCode() != 200) {
                    throw new RuntimeException("Failed : HTTP error code : "
                            + conn.getResponseCode());
                }

                BufferedReader br = new BufferedReader(new InputStreamReader(
                        (conn.getInputStream())));

                String output;
                System.out.println("Output from Server .... \n");
                while ((output = br.readLine()) != null) {
                    System.out.println(output);
                }
                conn.disconnect();
            }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }catch (IOException e){
        e.printStackTrace();
    }finally
        {
            if(conn != null)
            {
                conn.disconnect();
            }
        }
    }
}

这篇关于将Java与Python Flask连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆