Question

I am trying to connect from java android program to a http website. I am trying this code. But apparently, the code does not go pass the "client.execute()" statement. I have commented a return statement after execute and it does not go passed that. Am i missing something?

I had tried pretty the same code and it didnt work so i did copy the exact same code form Newboston and it still doesn't work.

(Code from Newboston.)

Thank you in advance.

public class GetMethodEx {

public String getInternetData() throws Exception{
    BufferedReader in=null;
    String data=null;

    try{
        HttpClient client=new DefaultHttpClient();
        URI website=new URI("http://www.mybringback.com");
        HttpGet request=new HttpGet();
        request.setURI(website);

        HttpResponse response=client.execute(request);

    //  if(data==null)
    //      return "bfdvhf";

        in =new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer sb=new StringBuffer("");
        String l="";
        String nl=System.getProperty("line.separator");

        while((l=in.readLine())!=null){
            sb.append(l + nl);
            return "hfeuhfuie";

        }
        in.close();
        data=sb.toString();
        return data;
    }finally{
        if(in!=null)
        {
            try{
                in.close();
                return data;

            }
            catch(Exception e){
                e.printStackTrace();

            }

        }
    }


}

}

Was it helpful?

Solution

Does your app crashes/throws exception on execute()? If so, you most likely getting NetworkOnMainThreadException exception - it is related to networking on UI thread (i.e trying to network directly in your Activity class). You have to separate networking and run this code asynchrously (usually using IntentService or AsyncTask).

See this article for more information.

BTW: next time always post your logcat output with your question

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top