JAVA和FLASK实现参数传递(亲测)

JAVA:httpclient4.5-14.jar

复制代码
package HttpFlask;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HTTPFlask {
    // 测试get请求
    public static void main(String[] args){

        // 测试带参数的GET
        Map<String, String> params1 = new HashMap<>();
        params1.put("name", "huitao");
        getWithParams("http://127.0.0.1:5000/", params1);

        //测试带参数的POST
        Map<String, String> params2 = new HashMap<>();
        params2.put("userId", "1");
        params2.put("name", "tech");
        String less=postFormData("http://127.0.0.1:5000/add/", params2);
        System.out.print(less);

    }
    /**
     * 发送JSON格式的POST请求到Python模型服务
     */
    public static String postJsonToPythonModel(String url, String jsonData) {
        HttpClient httpClient = HttpClients.createDefault();

        try {
            HttpPost httpPost = new HttpPost(url);

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("User-Agent", "Java-HttpClient");

            // 设置请求体
            StringEntity entity = new StringEntity(jsonData, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);

            // 执行请求
            HttpResponse response = httpClient.execute(httpPost);

            // 检查状态码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode >= 200 && statusCode < 300) {
                HttpEntity responseEntity = response.getEntity();
                return responseEntity != null ? EntityUtils.toString(responseEntity) : null;
            } else {
                System.err.println("HTTP错误: " + statusCode);
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 发送表单格式的POST请求
     */
    public static String postFormData(String url, Map<String, String> formData) {
        HttpClient httpClient = HttpClients.createDefault();

        try {
            HttpPost httpPost = new HttpPost(url);

            // 构建表单数据
            List<NameValuePair> params = new ArrayList<>();
            for (Map.Entry<String, String> entry : formData.entrySet()) {
                params.add(new org.apache.http.message.BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            httpPost.setEntity(new org.apache.http.client.entity.UrlEncodedFormEntity(params, "UTF-8"));

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String str=toString(entity);
//            System.out.print(str);
//            return entity != null ? EntityUtils.toString(entity) : null;
            return str;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //Httpget请求示例
    public static void simpleGet(String url) {
        HttpClient httpClient = HttpClients.createDefault();

        try {
            // 创建GET请求
            HttpGet httpGet = new HttpGet(url);

            // 设置请求头
            httpGet.setHeader("User-Agent", "Mozilla/5.0");
            httpGet.setHeader("Accept", "application/json");

            // 执行请求
            HttpResponse response = httpClient.execute(httpGet);

            // 获取状态码
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("状态码: " + statusCode);

            // 获取响应内容
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity);
                System.out.println("响应内容: " + result);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void getWithParams(String url, Map<String, String> params) {
        HttpClient httpClient = HttpClients.createDefault();

        try {
            // 构建带参数的URL
            if (params != null && !params.isEmpty()) {
                StringBuilder urlBuilder = new StringBuilder(url);
                urlBuilder.append("?");
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    urlBuilder.append(entry.getKey())
                            .append("=")
                            .append(java.net.URLEncoder.encode(entry.getValue(), "UTF-8"))
                            .append("&");
                }
                url = urlBuilder.substring(0, urlBuilder.length() - 1); // 移除最后一个&
            }

            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity);
                System.out.println("GET请求结果: " + result);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送文件到服务器
    public static void FileUploadUtils(){

    }

    public static String toString(HttpEntity entity) throws IOException {
        //获取一个含有实体信息的流
        InputStream inStream = entity.getContent();
        if (inStream == null) {
            return null;
        }

        //从流中读取数据
        Reader reader = new InputStreamReader(inStream, "UTF-8");
        CharArrayBuffer buffer = new CharArrayBuffer(100);
        char[] tmp = new char[1024];
        int l;
        while ((l = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, l);
        }
        reader.close();
        return buffer.toString();
    }

}

flask:

复制代码
from flask import Flask, jsonify,request

app = Flask(__name__)


@app.route('/',methods=['GET'])
def hello_world():
    # return 'Hello World!'
    name = request.form.get("name")
    if name == 'huitao':
        return jsonify({"code": 200, "message": "success", "data": "欢迎!!"})
    else:
        return jsonify({"code": 200, "message": "success", "data": "参数传递错误"})



@app.route('/add/', methods=['POST'])
def add_numbers():
    # request.form.get:获取post请求的参数,
    userId = request.form.get("userId")
    name = request.form.get("name")
    print("userid:",userId)
    print("name:",name)
    return jsonify({"code":200,"message":"success"})



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

测试结果:

相关推荐
froginwe112 小时前
HTML 表格
开发语言
一只小松许️2 小时前
深入理解 Rust 的内存模型:变量、值与指针
java·开发语言·rust
无限进步_3 小时前
【C语言】寻找数组中唯一不重复的元素
c语言·开发语言·算法
A阳俊yi3 小时前
Spring——事件机制
java·后端·spring
Fency咖啡3 小时前
Spring进阶 - SpringMVC实现原理(二)DispatcherServlet处理请求的过程
java·后端·spring·mvc
m0_651593914 小时前
位置透明性、Spring Cloud Gateway与reactor响应式编程的关系
java·spring cloud·系统架构·gateway
玉树临风江流儿4 小时前
Cmake使用CPack实现打包
java·服务器·前端
yunmi_4 小时前
微服务,Spring Cloud 和 Eureka:服务发现工具
java·spring boot·spring cloud·微服务·eureka·架构·服务发现
一叶飘零_sweeeet4 小时前
从 0 到 PB 级存储:MinIO 分布式文件系统实战指南与架构解密
java·架构·大文件存储