0

First of i'm a noob when it comes to android/java, i just started looking into it this week.

I have been searching the internet and trying out different things all day to find out how to get the contents of a webpage into a string in java (without webview). everything to be found is either deprecated or it's my lack of understanding that stands in my way, i've been reading documentation and everything but it just gets my head spinning, even though the task seems to be so simple, in php it just requires one function: file_get_contents()

I am able to do this using a invisible WebView, but as far as i know that's not the way to go, plus i also want to be able to post stuff to a webpage (though i might be able to do that by performing some javascript on the webview, but still that doesn't seem to be the way to go).

Can someone please give me a simple example of how to get the contents of a webpage into a string and a simple example to post something to a webpage (and retrieve the response into a string)

If possible with some explanation, but if i get a working example i can figure out why it works.

Henk
  • 142
  • 9
  • 1
    Look into this http://stackoverflow.com/questions/1485708/how-do-i-do-a-http-get-in-java – Yohannes Gebremariam Mar 03 '17 at 19:08
  • @YohannesGebremariam I don't understand this exception thing (this is what i run in with multiple "solutions" i've tried today).. what i did was copy that code and make a new java file out of it, then in my main file i call c.getHTML("http://www.google.com") to be put into a textview, but when i dod that android-studio forces me to put try catch stuff around it so i do that but it always results in the catch (i know this because in the catch i give another string to the textview) – Henk Mar 03 '17 at 19:53
  • Please post your exception, and what you have tried – Yohannes Gebremariam Mar 03 '17 at 19:56
  • @YohannesGebremariam i assume you mean somehow somewhere i can pull a exception error, but i don't know how that works.. this is what i have: tv = (TextView) findViewById(R.id.textView); try { tv.setText(c.getHTML("http://192.168.0.241/bla.php")); } catch (Exception e) { e.printStackTrace(); tv.setText("ow"); } – Henk Mar 03 '17 at 20:03
  • @YohannesGebremariam if i put e.getMessage() in the textview it remains empty for what it matters. – Henk Mar 03 '17 at 22:07

1 Answers1

2

For anyone that might come across this, i've solved it with the following code (this includes adding post parameters, if you want/need to):

private class GetContents extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... p) {
            String targetURL = p[0];
            String urlParameters = p[1];
        URL url;
        HttpURLConnection connection = null;
        try {
            //Create connection
            url = new URL(targetURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");

            connection.setRequestProperty("Content-Length", "" +
                    Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");

            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            //Send request
            DataOutputStream wr = new DataOutputStream(
                    connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            //Get Response
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();

        } catch (Exception e) {

            e.printStackTrace();
            return null;

        } finally {

            if (connection != null) {
                connection.disconnect();
            }
        }


        }

        protected void onPostExecute(String result) {
            // do something
        }
    }

And then using it like: new GetContents.execute("http://example.com", "a=b");

Henk
  • 142
  • 9