我在flask中有一个获取参数的项目,如果我通过邮递员进行调用,它可以工作。但是如果我按照java代码来做,它会返回错误400。
烧瓶:
@app.route('/predict', methods=["POST"])
def predict():
print("\nPredict......")
print(request.form)
print(request.form['textToPredict'])
print("\nPredict......2")
print(request.form.get("textToPredict"))
#print("Text...."+request.form['textToPredict'].toString())
# new text to predict
text_to_predict = [request.form['textToPredict'].lower()] #[request.form.get('textToPredict')] # ["asmatica desde infancia ex fumante 15 am dopc em uso de o2 ha 1 ano em uso de alenia 400 /12 e formoterol 12 2 x dia mvdiminuido sra brn f 2 t s/s cta rx pfp"] # este deve retornar CID Z00
#print("Text....:"+str(text_to_predict))
# count_vect gera as posições dos vetores de cada palavra do texto.
new = count_vect.transform(text_to_predict)
# carrega o modelo treinado
loaded_model = cPickle.load(open(fname, 'rb'))
# faz a predição do novo texto de entrada
result = loaded_model.predict(new)
print(result)
# accuracy_score(y_test, result)
json_dict = request.get_json()
text = ''.join(result)
textPredicted = text
data = {'textPredicted': textPredicted}
return jsonify(data), 200
java的输出(打印FLASK代码):
Predict......
ImmutableMultiDict([('{"textToPredict":"coriza"}', '')])
127.0.0.1 - - [22/Oct/2018 16:07:34] "POST /predict HTTP/1.1" 400 -
邮递员的输出(打印烧瓶代码):
Predict......
ImmutableMultiDict([('textToPredict', 'coriza, dificuldade em respirar, febre, dor no corpo')])
coriza, dificuldade em respirar, febre, dor no corpo
Predict......2
coriza, dificuldade em respirar, febre, dor no corpo
['J06 ']
127.0.0.1 - - [22/Oct/2018 16:20:00] "POST /predict HTTP/1.1" 200 -
Java代码:
@POST
// @Path("")
private String predictCid(String predicaoVo) throws IOException {
System.out.print("\nentrou no método predict");
try {
JSONObject jsonParam = new JSONObject();
jsonParam.put("textToPredict", predicaoVo);
String PARAMETROS = "{\ntextToPredict:"+predicaoVo+"\n}";
URL url = new URL("http://127.0.0.1:5000/predict");
HttpURLConnection postConnection = (HttpURLConnection) url.openConnection();
postConnection.setRequestMethod("POST");
postConnection.setRequestProperty("content-Type", "application/x-www-form-urlencoded");
postConnection.setUseCaches(false);
postConnection.setDoInput(true);
postConnection.setDoOutput(true);
// Send POST output.
DataOutputStream printout = new DataOutputStream(postConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(printout, "UTF-8"));
System.out.print("\nParametros: "+jsonParam.toString());
writer.write(jsonParam.toString());
writer.flush();
writer.close();
//printout.writeBytes(jsonParam.toString());
//printout.flush();
printout.close();
int responseCode = postConnection.getResponseCode();
System.out.println("POST Response Code : " + responseCode);
System.out.println("POST Response Message : " + postConnection.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
return response.toString();
} else {
System.out.println("POST NOT WORKED");
}
} catch (Exception ex) {
ex.printStackTrace();
}
return "some string just to test"; // just a test
}
所以,看起来,我的错误是在发送帖子时,它是由java代码组成的。
我不能理解错误的原因。在我看来,当到达烧瓶时,参数是不正确的,从它提供的输出来看。
我想要一些帮助来解决这个问题。谢谢。
发布于 2018-10-23 04:00:46
您的java代码不正确,因为您正试图将json对象字符串发送到表单url编码的数据中。看起来像你的Flask控制器期望的表单参数。您可以像这样更改java代码。
String urlParam = "textToPredict="+predicaoVo;
byte[] postData = urlParam.getBytes( StandardCharsets.UTF_8 );
int dataLength = postData.length;
postConnection.setRequestProperty( "Content-Length", Integer.toString(dataLength));
try( DataOutputStream wr = new DataOutputStream(postConnection.getOutputStream())) {
wr.write(postData);
}
https://stackoverflow.com/questions/52936456
复制相似问题