如何访问从Android的一个Web API方法的返回值? [英] How do I access the returned value from a Web API Method in Android?

查看:338
本文介绍了如何访问从Android的一个Web API方法的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

混淆有关如何做到这一点(可以看出<经过href="http://stackoverflow.com/questions/22797194/how-to-call-a-restful-method-from-android">here和<一href="http://stackoverflow.com/questions/22798949/why-is-my-web-api-server-refusing-to-accept-calls-from-android">here,我现在成功地连接到我的服务器应用程序及相应的REST风格的方法与此code:

After being confused about how to do so (as can be seen here and here, I am now successfully connecting to my server app and the appropriate RESTful method with this code:

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,但什么? 在我需要访问/隐蔽的字符串什么的一部分?

I realize I need to assign something (other than an empty string at initialization) to resultToDisplay, but what? What part of "in" do I need to access/covert to a string?

手工的方式为我工作,但fancypants apache的IO utils的没有那么多(当然,它编译...)。这是我的code:

The "manual" way is working for me, but the fancypants apache io utils "not so much" (well, it compiles...). This is my code:

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)。总的分配不会(我得到的,)。

resultToDisplay's assignment works (I get, "18"). total's assignment does not (I get, "").

注意:在getStringFromInputStream()方法是Raghunandan的链接

Note: The "getStringFromInputStream()" method is from Raghunandan's link.

这工作只是花花公子(使用WIllJBD的主意,使用Apache的百科全书'IOUtils):

This works just dandy (using WIllJBD's idea to use 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);
    }
}

...等等显然它不必添加任何东西,如编译的文件(库/公地-IO-2.4.jar')到build.gradle的依赖关系部分,因为似乎是至少必要在有一段时间,根据的这个。如果任何人都可以验证这样的[M,PP] en​​dments到build.gradle不再需要,我会gradleful。

...and so apparently it is not necessary to add anything like "compile files('libs/commons-io-2.4.jar')" to the dependencies section of build.gradle, as seemingly was at least necessary at one time, according to this. If anybody can verify such a[m,pp]endments to build.gradle are no longer needed, I'd be gradleful.

我只注意到我无意中删除了@覆盖从onPostExecute()方法,但它并没有区别 - 它工作得很好,没有它,它工作正常,一旦我恢复了它。那么,有什么的[不]有它的优势 - 它只是多余的绒毛

I just noticed that I inadvertently removed the "@Override" from the onPostExecute() method, but it made no difference - it worked fine without it, and it works fine once I restored it. So what's the advantage of [not] having it - is it just superfluous fluff?

推荐答案

为什么不使用类似IOUtils?

why not use something like 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,采用了许多图书馆之一。

now you can parse the string into Json or XML, using one of many libraries.

这篇关于如何访问从Android的一个Web API方法的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆