Need help solving a problem! Recently I began to learn programming for Android, and a problem arose that I can not solve. It is necessary to send requests with parameters to the post resource. As frontend I use python flask. Python code:
from flask import Flask from flask import request app = Flask(__name__) @app.route('/', methods=['POST']) def hello_world(): print request.json return 'True' if __name__ == '__main__': app.run(host='192.168.1.100', port='5000') Everything is okay like, tritely simple and without problems, and most importantly it works. But with the sadness of Android, I use the okhttp module. Here is the code:
package com.example.sanek.lessons1; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import org.json.JSONObject; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class MainActivity extends AppCompatActivity { public static final MediaType JSON = MediaType.parse("application/json charset=utf-8"); OkHttpClient client = new OkHttpClient(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onBtnPress(View view) { String json = "{'test':'1'}"; post("http://192.168.1.100:5000/", json, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String responseStr = response.body().string(); } else { } } }); } Call post(String url, String json, Callback callback) { try { JSONObject obj = new JSONObject(json); Log.d("My App", obj.toString()); } catch (Throwable t) { Log.e("My App", "Could not parse malformed JSON: \"" + json + "\""); } RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); Call call = client.newCall(request); call.enqueue(callback); return call; } } When you click on the button in the Android application, you must send a post request with the parameter "{'test': '1'}". The request is sent, here is the answer python flask
None 192.168.1.107 - - [23/Jun/2016 19:59:57] "POST / HTTP/1.1" 200 - The request comes, only for some reason the parameters do not come, more precisely, there is None. What am I doing wrong? Maybe there are some other solutions?
print request.jsonto understand what is coming. If there is your json, then the problem is somewhere in the parsing on the server. - lllyctMediaType.parse("application/json; charset=utf-8")- lllyct