我正在尝试将JSON格式的字符串从Android设备发送到Flask服务器。我正在使用Apache MultiPartEntityBuilder进行发送,因为我还想在同一个http post消息中发送图像文件。我发送和接收文件没有问题,但由于某种原因,JSON数据没有按照我在Flask方面的预期处理。我期望可以使用request.get_json()在Flask中访问JSON数据,但由于某种原因,这没有任何帮助。相反,使用request.form可以访问JSON数据。因此,Flask服务器可能由于某种原因无法识别JSON数据。或者request.get_json()甚至可以处理多部分数据?
在Android中发送JSON:
public void postJson() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("message", "Hello World!");
} catch (JSONException e) {
e.printStackTrace();
}
try{
HttpClient httpclient = createHttpClient();
HttpPost httpPost = new HttpPost("http://server/jsontest/");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addTextBody("json", jsonObject.toString(), ContentType.APPLICATION_JSON);
httpPost.setEntity(builder.build());
HttpResponse response = httpclient.execute(httpPost);
int code = response.getStatusLine().getStatusCode();
Toast.makeText(getBaseContext(), "Status code = " + code, Toast.LENGTH_LONG).show();
} catch(Exception e){
Log.e(LOG_TAG, "Error in http connection" + e.toString());
}
}
在FLASK中接收JSON:
from flask import Flask
from flask import jsonify
from flask import request
app = Flask(__name__)
if not app.debug:
import logging
from logging.handlers import RotatingFileHandler
file_handler = RotatingFileHandler('app.log', 'a', 1 * 1024 * 1024, 10)
file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(filename)s:%(lineno)d]'))
app.logger.setLevel(logging.DEBUG)
file_handler.setLevel(logging.DEBUG)
app.logger.addHandler(file_handler)
app.logger.info('App startup')
@app.route('/', methods=['GET', 'POST'])
def get_json():
app.logger.info('Start of get_json')
app.logger.info('Form data')
app.logger.info(request.form)
app.logger.info('Json data')
app.logger.info(request.get_json())
return 'OK'
记录文件内容:
2013-12-31 11:57:10,600 INFO: App startup [in app.py:15]
2013-12-31 11:57:10,622 INFO: Start of get_json [in app.py:19]
2013-12-31 11:57:10,624 INFO: Form data [in app.py:21]
2013-12-31 11:57:10,629 INFO: ImmutableMultiDict([('json', u'{"message":"Hello World!"}')]) [in app.py:22]
2013-12-31 11:57:10,632 INFO: Json data [in app.py:24]
2013-12-31 11:57:10,635 INFO: None [in app.py:25]
答案 0 :(得分:3)
您正在创建一个带有json
参数的多部分编码POST正文,这在发布表单数据时非常有用。
要发布只是 JSON(要request.json
和request.get_json()
才能工作),您必须发布数据而不用将其编码为多个 - 身体:
HttpClient httpclient = createHttpClient();
HttpPost httpPost = new HttpPost("http://server/jsontest/");
httpPost.setHeader(ContentType.APPLICATION_JSON);
httpPost.setEntity(jsonObject.toString());
HttpResponse response = httpclient.execute(httpPost);
请注意,您需要设置application/json
内容类型标头。我不太熟悉Android Java类,我猜测ContentType.APPLICATION_JSON
是一个Header
对象,您可以直接在httpPost
对象上设置。