如何从Android中的Web API方法访问返回的值?

时间:2014-04-02 17:05:09

标签: java android android-asynctask http-get bufferedinputstream

在对如何操作感到困惑之后(可以看到herehere,我现在使用此代码成功连接到我的服务器应用程序和相应的RESTful方法:

public void onFetchBtnClicked(View v){
    if(v.getId() == R.id.FetchBtn){
        Toast.makeText(getApplicationContext(), "You mashed the button, dude.", Toast.LENGTH_SHORT).show();
    new CallAPI().execute("http://10.0.2.2:28642/api/Departments/GetCount?serialNum=4242");
    }
}

public static class CallAPI extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {

        String urlString=params[0]; // URL to call
        String resultToDisplay = "";
        InputStream in = null;

        // HTTP Get
        try {
            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedInputStream(urlConnection.getInputStream());
        } catch (Exception e ) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
        return resultToDisplay;

    }

    protected void onPostExecute(String result) {
        Log.i("FromOnPostExecute", result);
    }

} // end CallAPI

我意识到我需要在resultToDisplay中分配一些东西(初始化时除了空字符串),但是什么?我需要访问/隐藏字符串“in”的哪一部分?

更新

“手动”方式对我有用,但是fancypants apache io utils“不是那么多”(好吧,它编译......)。这是我的代码:

try {
    URL url = new URL(urlString);
    HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
    in = new BufferedInputStream(urlConnection.getInputStream());
    resultToDisplay = getStringFromInputStream(in);
    total = IOUtils.toString(in);

resultToDisplay的作业有效(我知道,“18”)。总的分配没有(我得到,“”)。

注意:“getStringFromInputStream()”方法来自Raghunandan的链接。

更新2

这只是花花公子(使用WIllJBD的想法来使用apache commons'IOUtils):

new CallWebAPI().execute("http://10.0.2.2:28642/api/Departments/GetCount?serialNum=4242");
. . .
private class CallWebAPI extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {

        String urlString=params[0]; // URL to call
        String result = "";

        // HTTP Get
        try {
            URL url = new URL(urlString);
            HttpURLConnection urlConnection =  
                (HttpURLConnection)url.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            if (null != inputStream)
                result= IOUtils.toString(inputStream);
        } catch (Exception e ) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        Log.i("RenameTheWashingtonFootballTeamTheRedskinPeanuts", result);
    }
}

...显然没有必要在build.gradle的依赖项部分添加类似“编译文件('libs / commons-io-2.4.jar')”的内容,因为看起来至少是必要的根据{{​​3}},有一次。如果任何人都可以验证不再需要build.gradle这样的[m,pp]结尾,那我就会很鄙视。

更新4

我只是注意到我无意中从onPostExecute()方法中删除了“@Override”,但它没有任何区别 - 没有它它工作正常,并且一旦我恢复它就可以正常工作。那么[没有]它的优点是什么 - 它只是多余的绒毛?

1 个答案:

答案 0 :(得分:1)

为什么不使用像IOUtils这样的东西?

InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null)
    String content = IOUtils.toString(inputStream);

http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html

现在您可以使用众多库中的一个将字符串解析为Json或XML。