1

我正在尝试从 java android 程序连接到 http 网站。我正在尝试这段代码。但显然,代码没有通过“client.execute()”语句。我在执行后评论了一个返回语句,但它没有通过。我错过了什么吗?

我尝试了几乎相同的代码,但它没有用,所以我确实从 Newboston 复制了完全相同的代码,但它仍然不起作用。

(来自纽波士顿的代码。)

先感谢您。

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

            }

        }
    }


}

}

4

1 回答 1

2

您的应用程序是否崩溃/抛出异常execute()?如果是这样,您很可能会收到NetworkOnMainThreadException异常 - 它与 UI 线程上的网络有关(即尝试直接在您的 Activity 类中进行网络连接)。您必须分离网络并异步运行此代码(通常使用IntentServiceor AsyncTask)。

有关更多信息,请参阅本文

顺便说一句:下次总是用你的问题发布你的 logcat 输出

于 2012-11-22T23:15:47.773 回答