Python服务端
from flask import Flask, request class AiServer(object): def __init__(self): server = Flask(__name__) server.route('/post', methods=['POST'])(self.post) server.run(host="0.0.0.0", port=8000, threaded=True) def post(self): if request.method == "POST": print("get post") response_data = request.json print("response_data", response_data) return "Hello" if __name__ == '__main__': AiServer()
Java客户端
import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; public class App { public static void main(String args[]){ HttpURLConnection conn = null; DataOutputStream os = null; try{ URL url = new URL("http://localhost:8000/post"); //important to add the trailing slash after add String inputData = "{\"x\": 5, \"y\": 8, \"text\":\"random text\"}"; byte[] postData = inputData.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(inputData.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(); } } } }