简体   繁体   中英

How to return JSON object from flask

I am trying to retun JSON object from my flask server but only thing it retun is OK string.

enter code here


from flask import Flask, request,jsonify,json
app = Flask(__name__)

@app.route('/')
def WelcomeToDataMining():
  return 'Welcome To Data Mining'

@app.route('/search/', methods=['POST']) 
def searchText():
   req_data = request.get_json()
   searchdata = req_data['searchString']
   print(searchdata)
   #return "hello return"
   data = {'movie':'XYZ','Description':'Hello XYZ'}
   print(jsonify(data))
   return jsonify(data)

if __name__ == '__main__':
   app.run()

` After receiving POST msg I am able to print received string but response is always ok.

Output at server after receiving POST msg.
Hello XYZ ABC
127.0.0.1 - - [09/Feb/2019 16:15:06] "POST /search/ HTTP/1.1" 200 -
<Response 42 bytes [200 OK]>

Error at client side
D/Received Joson Exp: org.json.JSONException: Value OK of type 
java.lang.String cannot be converted to JSONObject

package com.example.serverconnection;
import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONObject;
import org.json.JSONException;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class ConnectServer {

//reason for 10.0.2.2 is 
https://developer.android.com/studio/run/emulator- 
networking
String SearchURL = "http://10.0.2.2:5000/search/";
JSONObject searchResponse;
//String SearchURL = "http://stackoverflow.com";
String SearchData;
private class HTTPAsyncTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... strings) {
        return getResponseFromServer(strings[0]);
    }

    @Override
    protected void onPostExecute(String Response){
        if (Response != null) {
            try {
                searchResponse = new JSONObject(Response);
                Log.d("Received", Response);
            } catch (JSONException e) {
                Log.d("Received Joson Exp", e.toString());;
            }

        }
    }
}

public void SendSearchData(String data){
    SearchData = data;
    new HTTPAsyncTask().execute(SearchURL);
}

private String getResponseFromServer(String targetUrl){
    try {
        //creating Http URL connection
        URL url = new URL(targetUrl);
        HttpURLConnection urlConnection = (HttpURLConnection) 
 url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type", 
"application/json");

        //building json object
        JSONObject jsonObject = CreateSearchJson();



        //Creating content to sent to server
        CreateDatatoSend(urlConnection, jsonObject);

        //making POST request to URl
        urlConnection.connect();



        //return response message
        return urlConnection.getResponseMessage();

    } catch (MalformedURLException e) {
        Log.d("JCF","URL failed");
    } catch (IOException e) {
        Log.d("JCF","IO Exception getResponseFromServer");;
    }
    return null;
 }

private JSONObject CreateSearchJson() {

    JSONObject jsonsearchObject = new JSONObject();
    try{
        jsonsearchObject.put("searchString",SearchData);
        return jsonsearchObject;
    }catch (JSONException e){
        Log.d("JCF","Can't format JSON OBject class: Connect servet Method 
: 
CreateSearchJson");
    }
    return null;
}

private void CreateDatatoSend(HttpURLConnection urlConnection,JSONObject 
JObject){
    try {
        urlConnection.setDoOutput(true);
        urlConnection.setChunkedStreamingMode(0);
        Log.d("JCF",JObject.toString());
        OutputStream os = new 
BufferedOutputStream(urlConnection.getOutputStream());
        //writeStream(os);

        //BufferedWriter writer = new BufferedWriter(new 
OutputStreamWriter(os, "UTF-8"));
        //writer.write(JObject.toString());
        //Log.i(MainActivity.class.toString(), JObject.toString());
        os.write(JObject.toString().getBytes());
        os.flush();
        //writer.flush();
        //writer.close();
        os.close();
    } catch (IOException e) {
        Log.d("JCF","set Post failed CreateDatatoSend");
    }

  }
}

Java side code is added, I am using android studio to connect to flsk web using http post message. I want to send and receive JSON object from android

I suspect your problem is

searchResponse = new JSONObject(Response);

which appears to be attempting to convert a response, rather than the response content, to JSON.

Did you try this:

@app.route('/search/', methods=['POST']) 
def searchText():
   req_data = request.get_json()
   searchdata = req_data['searchString']

   return jsonify(
        movie='XYZ',
        Description='Hello XYZ'
    )

your output will be in our browser:

{
    'movie':'XYZ',
    'Description':'Hello XYZ'
}

Issue was with getResponseStream

Updated onPostExecute

    @Override
    protected void onPostExecute(String Response){
        if (Response != null && Response.compareTo("OK") == 0) {
            Log.d("Received", new String(Integer.toString(Response.length())) );
            fullresponse = readStream(searchin);
            ReadReceivedJson();
        }
        else {
            Log.d("Response ", "Response Failed onPostExecute");
        }
    }

Updated CreateDatatoSend urlConnection getInputStream()

 private void CreateDatatoSend(HttpURLConnection urlConnection,JSONObject JObject){
    try {
        urlConnection.setDoOutput(true);
        urlConnection.setChunkedStreamingMode(0);
        Log.d("JCF",JObject.toString());
        OutputStream os = new BufferedOutputStream(urlConnection.getOutputStream());

        os.write(JObject.toString().getBytes());
        os.flush();
        searchin = new BufferedInputStream(urlConnection.getInputStream());

        os.close();
    } catch (IOException e) {
        Log.d("JCF","set Post failed CreateDatatoSend");
    }

}

Added readStream

    private String readStream(InputStream in){
    BufferedInputStream bis = new BufferedInputStream(in);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    int result = 0;
    try {
        result = bis.read();
        while(result != -1) {
            byte b = (byte)result;
            buf.write(b);
            result = bis.read();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return buf.toString();
}

added ReadReceivedJson

    private void ReadReceivedJson(){
    Log.d("Full Received", fullresponse );
    try {
        searchResponse = new JSONObject(fullresponse);
    } catch (JSONException e) {
        Log.d("Received Joson Exp", e.toString());
    }
    try {
        JSONArray arrJson = searchResponse.getJSONArray("Movie");
        String Moviearr[] = new String[arrJson.length()];
        for(int i = 0; i < arrJson.length(); i++) {
            Moviearr[i] = arrJson.getString(i);
            Log.d("Movie", Moviearr[i]);
        }
    } catch (JSONException e) {
        Log.d("No Movie", fullresponse );
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM