dhruv
dhruv

Reputation: 31

How to get content of a URL and to read it in a android java application using eclipse

//Following code works fine but read's the source code as well as the content, I just need to read the content Thanks for the help.//

package t.n.e;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.xml.sax.Parser;

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;



public class urlgettingproject extends Activity {
    private EditText T1;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        T1 = (EditText)findViewById(R.id.T1);
        StringBuilder content = new StringBuilder();


        try {
            URL url = new URL("http://10.0.22.222:8080/SaveName.jsp?first=12&second=12&work=min");
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            while ((str = in.readLine()) != null) {
                content.append(str +"\n");
                T1.setText(content);
            }
            in.close();
        } catch (MalformedURLException e){
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Upvotes: 3

Views: 14615

Answers (1)

Vivienne Fosh
Vivienne Fosh

Reputation: 1778

Well, if you just need the content, why won't you simplify it this way:

    private InputStream OpenHttpConnection(String strURL)
            throws IOException {
        URLConnection conn = null;
        InputStream inputStream = null;
        URL url = new URL(strURL);
        conn = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            inputStream = httpConn.getInputStream();
        }
        return inputStream;
    }

And then just read the stream?

Upvotes: 3

Related Questions