【问题标题】:Http Connection from Android来自 Android 的 Http 连接
【发布时间】:2012-11-23 07:21:17
【问题描述】:

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

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

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

            }

        }
    }


}

}

【问题讨论】:

  • 如何调用getInternetData()?从一个活动?只是一个建议:任何 http 请求都应该在 Thread UI 之外运行。使用 AsyncTask。
  • 嘿,是的,我只是从活动中打电话。但即使我从一个活动中调用,它应该工作得很好,对吧?我已经准备好了代码,但是这一条语句导致了问题。
  • 在这一行,in =new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 和 e.printStackTrace 上放置断点。运行代码时会发生什么?
  • @JS_VIPER 在 Android Honeycomb 或更高版本上,您应该使用另一个线程来执行 HTTP 请求。查看 AsyncTask 文档:developer.android.com/reference/android/os/AsyncTask.html

标签: java android web-services java-server


【解决方案1】:

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

更多信息请参见this article

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

【讨论】:

  • 不,应用程序不会崩溃,我为此设置了一个异常,它只是打印异常。
  • 谢谢。我是这个领域的新手。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-15
相关资源
最近更新 更多