我尝试使用 Android studio 调用 SOAP 服务,但出现以下异常 android.os.NetworkOnMainThreadException
我知道应该是在主线程上运行网络调用时,但我正在使用异步任务,所以我希望不会出现此异常
@RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public void TEST()
{
new TESTROOT().doInBackground();
}
@SuppressLint("StaticFieldLeak")
@RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public class TESTROOT extends AsyncTask<Void, Void, Boolean> {
protected Boolean doInBackground(Void... voids) {
HttpURLConnection connection = null;
try
{
URL url = new URL("http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
connection.setRequestProperty("SOAPAction", "http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso/ListOfContinentsByName");
connection.setDoOutput(true);
}
catch (Exception e) {
}
OutputStream os = null;
try {
os = connection.getOutputStream();
} catch (Exception ex) {
runOnUiThread(new Runnable() {
@SuppressLint("ShowToast")
public void run() {
Toast.makeText(getApplicationContext(), "" + ex, Toast.LENGTH_LONG).show();
}
});
}
有人可以帮助我理解我做错了什么吗? 谢谢 安德里亚
new TESTROOT().doInBackground();
您不应该自己调用 doInBackground(),因为这样您就没有使用 asynctask。
以正常方式开始您的任务,例如
new TESTROOT().execute();