Jennifer
Jennifer

Reputation: 1852

How to read the web contents with android?

I have a method that should actually read the data from the web and returns the content as a String, but it is not working.I would be glad if you can help me out! I don't know where I screwed up. I added the INTERNET uses permission in the manifest file but doesn't work. Well, I tested on the emulator only.

public String getInternetData() throws Exception {
    BufferedReader in = null;// read info

     String response = null;
    try {
        HttpClient client = new DefaultHttpClient(); // default client
        // process application to handle data from web
        URI website = new URI("https://www.random.com");
        // get information from web
        HttpGet request = new HttpGet(); // get data

        InputStream inputStream = null;


        request.setURI(website);// connected and request
        // respons
        HttpResponse httpResponse = client.execute(request);

         int statutCode = httpResponse.getStatusLine().getStatusCode();
         int length = (int) httpResponse.getEntity().getContentLength();

         inputStream = httpResponse.getEntity().getContent();
         Reader reader = new InputStreamReader(inputStream, "UTF-8");

         int inChar;
       StringBuffer stringBuffer = new StringBuffer();

       while ((inChar = reader.read()) != -1) {
            stringBuffer.append((char) inChar);
        }

        response = stringBuffer.toString();
    } finally {

    }

return response; }

Upvotes: 0

Views: 74

Answers (1)

Barışcan Kayaoğlu
Barışcan Kayaoğlu

Reputation: 1304

I checked your code and it's working. I'm not sure if you are establishing a connection on your EDT or not but here's a template that's working with your code. Btw your link doesn't have a SSL, you need to connect to http.

package com.example.stackover;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            (new AsyncTask<Void, Void, Void>() {

                @Override
                protected Void doInBackground(Void... params) {
                    // TODO Auto-generated method stub
                    try {
                        getInternetData();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    return null;
                }

            }).execute();
            return rootView;
        }

        public void getInternetData() throws Exception {
            BufferedReader in = null;// read info

             String response = null;
            try {
                HttpClient client = new DefaultHttpClient(); // default client
                // process application to handle data from web
                URI website = new URI("http://www.random.com");
                // get information from web
                HttpGet request = new HttpGet(); // get data

                InputStream inputStream = null;


                request.setURI(website);// connected and request
                // respons
                HttpResponse httpResponse = client.execute(request);

                 int statutCode = httpResponse.getStatusLine().getStatusCode();
                 int length = (int) httpResponse.getEntity().getContentLength();

                 inputStream = httpResponse.getEntity().getContent();
                 Reader reader = new InputStreamReader(inputStream, "UTF-8");

                 int inChar;
               StringBuffer stringBuffer = new StringBuffer();

               while ((inChar = reader.read()) != -1) {
                    stringBuffer.append((char) inChar);
                }

                response = stringBuffer.toString();
            } finally {

            }
            Log.v("Information", response);
        }
    }

}

Upvotes: 1

Related Questions