我在Tomcat7服务器上部署了一个简单的java Web服务。我使用Axis2作为肥皂引擎。(Web服务和WSDL都可以) 这是我用于Web服务的代码
public class TestWs {
public String sayHello(){
return "Hello Grant";
}
}
我已经从Android 2.2访问过这个Web服务。这完全没问题。但是这个程序不适用于Android 4.0.3 我的Android程序代码
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.widget.TextView;
import android.app.Activity;
import android.os.Bundle;
public class AndroidWSClientActivity extends Activity {
private static final String SOAP_ACTION = "http://ws.android4.com/";
private static final String METHOD_NAME = "sayHello";
private static final String NAMESPACE = "http://ws.android4.com/sayHello/";
private static final String URL = "http://175.157.45.91:8085/ForAndroid4/services/TestWs?wsdl";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new
SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
try {
ht.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
String str = response.toString();
TextView result;
result = (TextView)findViewById(R.id.textView1);
result.setText(str);
} catch (Exception e) {
e.printStackTrace();
TextView result;
result = (TextView)findViewById(R.id.textView1);
result.setText("Error!");
}
}
}
程序正确安装在模拟器上。但是模拟器显示来自catch块的消息集。什么是错误???我怎么能纠正它? 谢谢!
答案 0 :(得分:1)
在Honeycomb和Ice Cream Sandwich(即Android 3.0+)中,你无法在主线程中连接到互联网(onCreate(),onPause(),onResume()等),你必须改为开始一个新线程。之所以发生变化,是因为网络操作会让应用程序等待很长时间,而如果你在主线程中运行它们,整个应用程序就会变得无法响应。 如果您尝试从主线程连接, Android将抛出NetworkOnMainThreadException。
答案 1 :(得分:0)