背景
JAVA调用PYTHON微服务。
JAVA调用
JAVA调用HTTP的POST请求案例
import jdk.nashorn.internal.parser.JSONParser;
import net.sf.json.JSONObject;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLEncoder;
public class Main {
public static void main(String[] args) throws IOException {
String urlStr = "http://ID/re_post";
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
//如果要使用URL连接进行输入,请将DoInput标志设置为true,否则将其设置为false
JSONObject json = new JSONObject();
json.put("productName", "鞋");
json.put("businCatA", "运动动户外运动户外");
json.put("businCatB", "运动鞋包");
json.put("businCatC", "跑步鞋跑步鞋跑步鞋跑步鞋跑步鞋跑步鞋");
con.setDoInput(true);
//如果要使用URL连接进行输出,请将DoInput标志设置为true,否则将其设置为false
con.setDoOutput (true);
con.setRequestMethod("POST");
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(),"UTF-8");
writer.write(json.toString());
writer.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(con.getInputStream()));
// JSONParser
// JSONObject
String response = "";
String tmp;
while((tmp=reader.readLine())!=null){
response += tmp;
}
JSONObject obj = JSONObject.fromObject(response);
System.out.println(response);
System.out.println("Hello World");
}
}
PYTHON接收
# 导入模板模块
from flask import render_template, request
# 从app模块中即从__init__.py中导入创建的app应用
from app import app
from flask import jsonify
from app.utils.host_utils import host_ip
from flask import Flask, request
import difflib
import json
# 建立路由,通过路由可以执行其覆盖的方法,可以多个路由指向同一个方法
@app.route("/")
@app.route("/index")
def index():
user = {'username': 'admin'}
# 将需要展示的数据传递给模板进行显示
return render_template('index.html', title='你好,世界', user=user)
@app.route("/reverse_post", methods=["POST"])
def reverse_post():
#解析ImmutableMultiDict
request_dicts = json.loads(list(request.form.to_dict().keys())[0])
productName = request_dicts["ptName"]
businCatA = request_dicts["batA"]
return {"productName":productName, "businCatA":businCatA}
@app.route("/set_test", methods=["GET"])
def send_test():
#商品名称
print("输入信息:", "")
productName = request.args.get("Name")
print("输入信息:",productName)
#一级品类
businCatA = request.args.get("businA")
#二级品
POST与GET请求调用总结
使用JAVA调用PYTHON服务亲自测试结论:
POST请求调用时不限制参数的长度。GET请求调用时限制参数长度。

被折叠的 条评论
为什么被折叠?



