如何使用flightstatus api它在android上返回null

时间:2013-03-02 12:54:05

标签: android api

我试图使用来自flightstatus.com的api获取航班状态

httpEntity.getContent();从网址

获取null

并且它给出了错误

status: 405
code: METHOD_NOT_ALLOWED
message: Method not allowed.

并且日志正在给出:

org.json.JSONException: Value status of type java.lang.String cannot be converted to JSONObject

请帮助

I'm using the following url

和以下代码

主要java类

package com.airportkwt;

import java.util.ArrayList;
import java.util.HashMap;

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

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class FlightStatus extends ListActivity {

    // url to make request
    private static String url = "https://api.flightstats.com/flex/flightstatus/rest/v2/json/airport/status/OKBK/dep/2013/2/27/13?appId=16decbe1&appKey=2ed0ada41c7ef6c31253ce11c93b8692&utc=false&numHours=6&maxFlights=10";

    // JSON Node names
    private static final String TAG_Array = "flightStatuses";
    private static final String TAG_ID = "flightId";
    private static final String TAG_DepAIrportCode = "departureAirportFsCode";
    private static final String TAG_ArrAIrportCode = "arrivalAirportFsCode";
    private static final String TAG_FlightNum = "flightNumber";

    // contacts JSONArray
    JSONArray contacts = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.flightstatus);

        if (android.os.Build.VERSION.SDK_INT > 9) {
              StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
              StrictMode.setThreadPolicy(policy);
            }






        // Hashmap for ListView
        ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        jsonParser jParser = new jsonParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of Contacts
            contacts = json.getJSONArray(TAG_Array);

            // looping through All Contacts
            for(int i = 0; i < contacts.length(); i++){
                JSONObject c = contacts.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString(TAG_ID);
                String name = c.getString(TAG_DepAIrportCode);
                String email = c.getString(TAG_ArrAIrportCode);
                String address = c.getString(TAG_FlightNum);


             // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_ID, id);
                map.put(TAG_DepAIrportCode, name);
                map.put(TAG_ArrAIrportCode, email);

                // adding HashList to ArrayList
                contactList.add(map);
            }



        } catch (JSONException e) {
            e.printStackTrace();
        }




        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, contactList,
                R.layout.list_departures,
                new String[] { TAG_DepAIrportCode, TAG_ArrAIrportCode }, new int[] {
                        R.id.name, R.id.email, R.id.mobile });

        setListAdapter(adapter);

jsonParser Java Class

package com.airportkwt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

public class jsonParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public jsonParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);


            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();          

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

1 个答案:

答案 0 :(得分:2)

我找到了解决方案

API返回休息和所需的休息请求而不是json

public static JSONObject queryRESTurl(String url) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response;

        try {
                response = httpclient.execute(httpget);
                Log.i("TAG", "Status:[" + response.getStatusLine().toString() + "]");
                HttpEntity entity = null;
                try{
                    entity = response.getEntity();
                }catch(Exception e){
                    Log.e("log_tag", "Error in http connection "+e.toString());
                }
                if (entity != null) {

                    InputStream instream = entity.getContent();

                        String result = RestClient.convertStreamToString(instream);
                        Log.i("TAG", "Result of converstion: [" + result + "]");

                        instream.close();
                        //return result;

                        try {
                            jObj = new JSONObject(result);
                        } catch (JSONException e) {
                            Log.e("JSON Parser", "Error parsing data " + e.toString());
                        }
                        return jObj;

                }
        } catch (ClientProtocolException e) {
                Log.e("REST", "There was a protocol based error", e);
        } catch (IOException e) {
                Log.e("REST", "There was an IO Stream related error", e);
        }

        return null;
    }