HttpResponse没有获得服务器返回的JSON

时间:2014-04-12 20:47:16

标签: android python json httpresponse

我有一个使用Flask的RESTful API服务器,它处理JSON请求,当我使用curl执行POST方法时,我得到了我想要的答案。

~$curl -i -H "Content-Type: application/json" -X POST -d '{"id":"3","aircraft":"PRVLL","origin":"SBME","destination":"SBFS","departure":"11:00","route":"MAPRO"}' http://radiant-harbor-4344.herokuapp.com/dublinAirport/
HTTP/1.1 201 CREATED
Content-Type: application/json
Date: Sat, 12 Apr 2014 20:11:18 GMT
Server: gunicorn/18.0
Content-Length: 166
Connection: keep-alive

{
  "flightPlan": {
  "aircraft": "PRVLL", 
  "departure": "11:00", 
  "destination": "SBFS", 
  "id": "3", 
  "origin": "SBME", 
  "route": "MAPRO"
}

但是当我尝试使用HttpResponse类来执行POST时,我会从URL获取所有内容。就像我向URL发出GET请求一样,而不是从JSON消息中获取响应。

这里是我的Java代码,我也尝试过使用EntityUtils,但我得到了相同的结果。

public JSONObject postJSONToUrl(String url,String jsonMsg)
{
    try 
    {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(jsonMsg));
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        HttpResponse httpResponse = httpClient.execute(httpPost);
        //inputStream = httpResponse.getEntity().getContent();
        String response = EntityUtils.toString(httpResponse.getEntity());
        //String jsonResponse = new String();
        //jsonResponse = convertStreamToString(inputStream);
        //Log.i("STRING_CONVERTED", jsonResponse);
        Log.i("STRING_CONVERTED", response);
        jsonObj = new JSONObject(response);  //jsonResponse

    } catch (Exception e) {
        Log.e("Exception", e.toString());
    }
    return jsonObj;
}

这是我的Python代码,服务器端: 基本上它会处理请求并返回JSON消息。

@app.route('/<airportName>/', methods = ['POST'])
def create_plans(airportName):
    if not request.json: #handle errors
        abort(400)
    expectedAirport = searchAirport(airportList, airportName);
    #here two lines of code just to get the {} off of the new airports, because now will be some content there
    if expectedAirport[0]=={}:
      expectedAirport.remove({})
    #
    flightPlan = {
        #'id': len(expectedAirport) + 1,             //Sincronize part
        'id': request.json['id'],
        'aircraft': request.json['aircraft'],
        'origin': request.json['origin'],
        'destination': request.json['destination'],
        'departure': request.json.get('departure'),
        'route': request.json.get('route')
    }
    expectedAirport.append(flightPlan)
    return jsonify( { 'flightPlan': flightPlan } ), 201

这个问题的答案可能与HttpResponse的工作方式或DefaultHttpClient.execute()的工作原理有关,因为CURL正在返回我想要的东西,而且这个方法不是。

0 个答案:

没有答案