2 回答

TA貢獻1865條經驗 獲得超7個贊
正如上面 @TallChuck 的評論所述,您需要替換或刪除 URL 中的空格
URL url = new URL("http://127.0.0.1:5000/add?x=100&y=12&text='Test'");
我建議使用請求對象來檢索 GET 調用中的參數。
請求對象
要訪問 Flask 中的傳入數據,您必須使用請求對象。請求對象保存來自請求的所有傳入數據,其中包括 mimetype、referrer、IP 地址、原始數據、HTTP 方法和標頭等。盡管請求對象保存的所有信息都可能有用,但我們只關注通常由端點調用者直接提供的數據。
正如在發布大量參數和數據的評論中提到的,此任務的更合適的實現可能是使用 POST 方法。
以下是后端 POST 相同實現的示例:
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 后端的簡單方法:
curl -d '{"x":5, "y":10}' -H "Content-Type: application/json" -X POST http://localhost:5000/add
使用Java發布請求:
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();
}
}
}
}

TA貢獻1807條經驗 獲得超9個贊
你的 python 代碼有一個嚴重的設計缺陷,這會產生一個非常危險的安全缺陷,并且(幸運的是,考慮到安全缺陷的存在)是你的代碼無法工作的原因。
在 URL 中的簡單字符串旁邊放置任何內容都是不好的做法,因為:
URL 應該是地址,從語義上講,將它們用作數據載體沒有什么意義
它通常需要雜亂的代碼來生成和讀?。ㄔ谀氖纠校黄仁褂?code>eval來解析請求,這是極其危險的)
URL 的規則要求對字符進行編碼(讀起來很糟糕
%20
等等)
如果您期望參數數量固定,則應該使用查詢參數,否則最好使用請求正文??紤]到你的邏輯是什么,我認為使用查詢參數在語義上會更好(所以你的請求看起來像/add?x=100&y=1
)。
一般來說,eval
是你的敵人,而不是你的朋友,并且eval
通過網絡發送給你的東西是你的敵人。
添加回答
舉報