Henk
Henk

Reputation: 201

Getting contents of webpage in a string in Java (similar to php's file_get_contents())

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.

Upvotes: 0

Views: 1749

Answers (1)

Henk
Henk

Reputation: 201

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

Upvotes: 2

Related Questions