连接并从打开的 API 获取 JSON 响应,HTTP

Connecting and getting JSON response from an open API , HTTP

我一直在尝试自己通过教程、文档和搜索问题来解决这个问题,但我找不到解决方案。我已通过教程连接,但我一直在尝试连接到 API。 Website。我一直在努力得到结果,但我在这方面没有足够的知识来自己解决。我 post 了解了我是如何尝试实现它的。 问题:如何获得 JSON 回复? 如果您需要更多信息,我会更新我的问题。如果您认为这是一个糟糕的问题 post 为什么我可以纠正自己。

public class JSONTesting extends ActionBarActivity {
    /*
     Example displayed on site: scala/exercise [master] http http://localhost:9000/exercises/category/forearms
     HTTP/1.1 200 OK
     Content-Length: 1606
     Content-Type: application/json
     **Search
     List All Exercises: http http://localhost:9000/exercises/
     Search By Muscle Group:  http http://localhost:9000/exercises/category/forearms
     Search By Letter:  http http://localhost:9000/exercises/a
      */
    TextView textView;
    String LINK = "http://10.0.3.2:9000/exercises/"; //Genymotion (10.0.3.2)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jsontesting);
        textView = (TextView) findViewById(R.id.textView);

        new HttpAsyncTask().execute(LINK + "");
    }

    public static String GET(String url) {
        InputStream inputStream = null;
        String result = "";
        try {
            // create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // make GET request to the given URL
            HttpGet httpget = new HttpGet(url);
            httpget.setHeader("Content-Type", "application/json");
            HttpResponse httpResponse = httpclient.execute(httpget);//HostConnection::get() New Host Connection established 0xa4816120, tid 1602

            // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();
            // convert inputstream to string
            if (inputStream != null) {
                result = convertInputStreamToString(inputStream);
            } else {
                result = "Did not work!";
            }
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
        return result;
    }

    private static String convertInputStreamToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            result += line;
        inputStream.close();
        return result;

    }


    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            return GET(urls[0]);
        }

        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
            textView.setText(result);
        }
    }

    // check network connection
    public boolean isConnected() { // Returns Connected
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
            return true;
        else
            return false;
    }
}

更新

public class JSONTesting extends ActionBarActivity {

    TextView textView;
    String LINK = "http://10.0.3.2:9000/exercises/"; //Genymotion (10.0.3.2)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jsontesting);
        textView = (TextView) findViewById(R.id.textView);
        new HttpAsyncTask().execute(LINK);
    }

    public static String GET(String url) {
        JSONArray finalResult = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
            StringBuilder builder = new StringBuilder();
            for (String line = null; (line = reader.readLine()) != null; ) {
                builder.append(line).append("\n");
            }
            JSONTokener tokener = new JSONTokener(builder.toString());
            finalResult = new JSONArray(tokener); //This is your JSON result
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
        return finalResult.toString();
    }


    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            return GET(urls[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
            textView.setText(result);
        }
    }
}

这是我用来从 HttpResponse 对象获取 JSON 响应的代码片段。尝试将您的 GET 方法更改为此。

public static String GET(String url) {
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        BufferedReader reader = new BufferedReader(new    InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        StringBuilder builder = new StringBuilder();
        for (String line = null; (line = reader.readLine()) != null;) {
            builder.append(line).append("\n");
        }
        JSONTokener tokener = new JSONTokener(builder.toString());
        JSONArray finalResult = new JSONArray(tokener); //This is your JSON result
    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }
    return finalResult.toString();
}