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

时间:2015-02-26 19:02:48

标签: android http androidhttpclient

我一直试图通过自己的教程,文档和搜索问题来解决这个问题,我无法找到解决方案。我通过教程连接,但我一直在尝试连接到API。 Website。{{3}}。我一直试图得到一个结果,但我没有足够的知识在这个领域自己解决它。我发布了我试图实现它的方式。 问题:如何获得JSON响应?如果您需要更多信息,我会更新我的问题。如果你认为这是一个糟糕的问题,为什么我可以纠正自己。

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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这是我用来从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();
}