我在android中使用Volley库并创建一个像这样的JsonObjectRequest:
String JsonUrl = "192.168.1.3/json.py";
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, JsonUrl, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
mTextView.setText("Json Response: " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("Error in recieving JSON Response");
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
这是我的Python代码(json.py):
import json
pythonDictionary = {'name':'Bob', 'age':44, 'isEmployed':True}
dictionaryToJson = json.dumps(pythonDictionary)
print(dictionaryToJson)
我很确定我的python代码不正确。 我的问题是如何在python中编写代码来发送&amp;使用Get或POST方法将JsonObjects接收到android?感谢。
答案 0 :(得分:2)
我用以下代码解决了这个问题:
Android代码:
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, JsonUrl, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = new JSONObject(response.toString());
String name = obj.getString("name");
String age = obj.getString("age");
data += "Name: " + name + "\nAge : " + age;
mTextView.setText(data);
}
catch (JSONException e) {
mTextView.setText(e.toString());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("Error in recieving JSON Response:\n" + error.toString());
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
Python代码:
from flask import Flask
import json
app = Flask(__name__)
@app.route('/', methods=['GET'])
def echo_msg():
pythonDictionary = {'name': 'Bob', 'age': 44, 'isEmployed': True}
dictionaryToJson = json.dumps(pythonDictionary)
return dictionaryToJson
if __name__ == '__main__':
app.run(host='0.0.0.0')
所以你可以为Python运行Flask web-server并像这样发送你的JsonObject(使用GET方法)。