微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java-Android上的HTTP请求

我非常绝望,这就是为什么我要你寻求帮助.我在android应用程序中有以下代码

public void OnButtonClick(View view) throws ClientProtocolException, IOException, Exception
{       
    URL yahoo = new URL("http://privyrobsi.sk/brigades/getBrigades.json");
    URLConnection yc = yahoo.openConnection();
    BufferedReader in = new BufferedReader(
                            new InputStreamReader(
                            yc.getInputStream()));
    String inputLine;

    EditText ET = (EditText) findViewById(R.id.editText2);
    while ((inputLine = in.readLine()) != null) ET.setText(ET.getText()+inputLine);         
    in.close();        
}

我从here获得了此代码,我只对其做了一点修改.
当我尝试将代码作为独立的Java应用程序运行时,它可以工作.但是,当我尝试在android中使用它时,仿真器说不幸的是,该应用程序停止了.
我从LogCat here保存了日志.
我的清单文件中也有uses-permission android:name =“ android.permission.INTERNET”.

解决方法:

您无法在主线程中执行网络操作.在asynctask中执行此操作.

更新:

您的logcat数据显示您有一个NetworOnMainThreadException.根据doc

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

This is only thrown for applications targeting the Honeycomb SDK or
higher. Applications targeting earlier SDK versions are allowed to do
networking on their main event loop threads, but it’s heavily
discouraged.

解:

如前所述,您必须使用其他线程来执行网络操作.您可以使用以下内容

>异步任务
> Differet工作者线程
>处理程序

检查此thread.这个问题的答案几乎涵盖了所有解决方

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐