在蜂窝中执行Http post时出错

mos*_*aar 3 apache post android http android-3.0-honeycomb

我有两个Android移动设备一个v2.3 api 9和一个v3.1蜂窝我想发布sms代码的http api链接.它变成了我在蜂窝中出现错误而其他移动设备工作正常,这就是代码

public void sendSMS(String phone_num, int password)
{
try
{               
    HttpClient hc = new DefaultHttpClient();
            HttpPost post = new HttpPost("http://www.google.com/");
    hc.execute(post); // I got an error here    
}
catch(IOException e)
{

    Log.e("error", "error");
}  
} 
Run Code Online (Sandbox Code Playgroud)

Jor*_*sys 11

在HoneyComb中启用StrictMode,您必须禁用它以避免NetworkOnMainThreadException

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
Run Code Online (Sandbox Code Playgroud)

但不建议使用Asynctask,在这里你可以找到一个例子:

http://developer.android.com/reference/android/os/AsyncTask.html


sha*_*irh 6

您正在体验这一点,因为Android Honeycomb中有一项新功能.如果你查看日志,你会发现你得到了NetworkOnMainThreadException例外

在Android Honeycomb中,有一个新的应用程序策略限制在主线程上执行耗时的调用.

如果您看到以下内容,请检查您的异常堆栈: StrictMode$AndroidBlockGuardPolicy.onNetwork

帮助我的是阅读本文,然后修复我的代码,不使用主要执行线程进行HTTP调用.


小智 5

100%工作解决方案!

上方放置您的以下代码super.onCreate下的protected void onCreate方法:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Run Code Online (Sandbox Code Playgroud)

Jorgesys的想法!谢谢他!希望它能解决你的问题〜