0

I use Volley library in android and create a JsonObjectRequest like this:

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);

and this is my Python Code (json.py):

import json

pythonDictionary = {'name':'Bob', 'age':44, 'isEmployed':True}
dictionaryToJson = json.dumps(pythonDictionary)
print(dictionaryToJson)

I'm pretty sure that my python code is not correct. My problem is that how can i write a code in python to send & receive JsonObjects to android with Get or POST method? Thanks.

Mostafa Fahimi
  • 510
  • 1
  • 8
  • 23
  • Besides that point. `localhost` will not work on your Android device. This has been answered again and again. http://stackoverflow.com/questions/4779963/how-can-i-access-my-localhost-from-my-android-device – OneCricketeer Dec 21 '16 at 23:18
  • I have web-server running – Mostafa Fahimi Dec 21 '16 at 23:18
  • I used my laptop ip. i edit my question – Mostafa Fahimi Dec 21 '16 at 23:19
  • `json.py` does not appear to be running from a web-server. Also, naming a file `json.py` will not work with the line `import json` – OneCricketeer Dec 21 '16 at 23:19
  • import json is fine. I used this code to communicate with android to python using socket and it worked fine but not working with volley – Mostafa Fahimi Dec 21 '16 at 23:20
  • Sure, but what is hosting your python files? Flask? Apache HTTP? – OneCricketeer Dec 21 '16 at 23:21
  • I can make this work with php code but don't know how to handle this with python coz i'm new with python. – Mostafa Fahimi Dec 21 '16 at 23:23
  • Unclear why you need Python, then if you can make this all work with PHP. Python has it's own web frameworks that can work with Apache, or you can run them separately. You have said yourself that you are "pretty sure that your python code is not correct", so you should start there. Fix the server-side before even touching the Android client. – OneCricketeer Dec 21 '16 at 23:25
  • My android client is 100% correct. Yes i can do it with php but i need to handle server side with python for some reason.I asked here though someone know how to fix this.Its a simple question – Mostafa Fahimi Dec 21 '16 at 23:27
  • And there's a big long [list of Python Web Frameworks](https://wiki.python.org/moin/WebFrameworks/). Basically, what I'm trying to say is that Apache is serving the plain text of your Python file - it should not be executing any Python code. – OneCricketeer Dec 21 '16 at 23:27
  • So how people send JsonRequest with POST using python? Thats my question. there is no way for this? – Mostafa Fahimi Dec 21 '16 at 23:29
  • 1
    There is a way, but you have to pick a server that can accept those requests. Like Flask is really popular, but you can use whatever, just not a plain text file, essentially. http://flask.pocoo.org/docs/0.12/quickstart/#http-methods – OneCricketeer Dec 21 '16 at 23:31
  • You probably know how you can send JsonObjects with POST or GET method in PHP. I want to do exacte same thing just with python. – Mostafa Fahimi Dec 21 '16 at 23:32
  • Ok i will check Flask.ty – Mostafa Fahimi Dec 21 '16 at 23:33
  • Check djangi-rest-framework – Emmanuel Mtali Dec 21 '16 at 23:45

1 Answers1

2

I solve this issue with this codes:

Android Code:

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 Code:

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')

So you can run Flask web-server for Python and send your JsonObject (with GET method) like this.

Mostafa Fahimi
  • 510
  • 1
  • 8
  • 23