4

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

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?

UPDATE

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's assignment works (I get, "18"). total's assignment does not (I get, "").

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

UPDATE 2

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

...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.

UPDATE 4

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?

Community
  • 1
  • 1
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 1
    check this http://www.mkyong.com/java/how-to-convert-inputstream-to-string-in-java/ – Raghunandan Apr 02 '14 at 17:07
  • 1
    possible duplicate of [Android Reading from an Input stream efficiently](http://stackoverflow.com/questions/2492076/android-reading-from-an-input-stream-efficiently) – Adam Stelmaszczyk Apr 02 '14 at 17:08
  • The code in Raghunandan's comment works like a charm bracelet. – B. Clay Shannon-B. Crow Raven Apr 02 '14 at 17:38
  • 1
    One thing to take into consideration, I do believe that once you read a inputstream to its end, trying to read from it once more will return nothing because you are at the end of the input stream. Depending on the inputstream you may look into using `mark()` and `reset()` to restore the input stream back to the beginning for reuse if `markSupported() = true;` other wise you have consumed the content of the inputstream and it will remain empty in further use. – WIllJBD Apr 02 '14 at 21:22
  • A quick google search for bufferedinputstream to string returned this result, http://stackoverflow.com/questions/5713857/bufferedinputstream-to-string-conversion This is probably your answer. – senthil Apr 02 '14 at 17:26

1 Answers1

3

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

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

WIllJBD
  • 6,144
  • 3
  • 34
  • 44