我正在尝试从我的烧瓶服务器中重新调整JSON对象,但这是唯一的事情 retun是可以的字符串。
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()
` 收到POST讯息后,我可以列印收到的字串,但回应 总是可以的。
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辅助代码,我正在使用android studio使用http发布消息连接到flsk网站。我想从android发送和接收JSON对象
答案 0 :(得分:1)
我怀疑您的问题是
searchResponse = new JSONObject(Response);
似乎正在尝试将响应而不是响应内容转换为JSON。
答案 1 :(得分:0)
您尝试过吗:
@app.route('/search/', methods=['POST'])
def searchText():
req_data = request.get_json()
searchdata = req_data['searchString']
return jsonify(
movie='XYZ',
Description='Hello XYZ'
)
您的输出将在我们的浏览器中:
{
'movie':'XYZ',
'Description':'Hello XYZ'
}
答案 2 :(得分:0)
问题与getResponseStream有关
已更新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");
}
}
更新了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");
}
}
添加了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();
}
添加了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 );
}