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

B. *_*non 5 java android http-get bufferedinputstream android-asynctask

在对如何执行此操作感到困惑之后(如此处和此处所示现在使用以下代码成功连接到我的服务器应用程序和适当的 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
Run Code Online (Sandbox Code Playgroud)

我意识到我需要向 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);
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

...所以显然没有必要将“编译文件('libs/commons-io-2.4.jar')”之类的内容添加到 build.gradle 的依赖项部分,因为看起来至少有一次是必要的,根据这个。如果有人可以验证不再需要对 build.gradle 的此类修正,我会很满意。

更新4

我只是注意到我无意中从 onPostExecute() 方法中删除了“@Override”,但这没有什么区别 - 没有它它工作得很好,一旦我恢复它它工作得很好。那么,不拥有它有什么好处——它只是多余的东西吗?

WIl*_*JBD 3

为什么不使用 IOUtils 之类的东西?

InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null)
    String content = IOUtils.toString(inputStream);
Run Code Online (Sandbox Code Playgroud)

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

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