我正在运行一个简单的项目,点击 android 中的一个按钮。显示从 Web 服务返回的消息,其编码是用 Java 完成的。
这是我在 eclipse for Android 中的程序:
@Override
public void onClick(View v) {
final String url = "http://10.0.2.2:8050/WebPractice/PracticeWebServices?wsdl";
final String namespace = "http://PracticeWebServices/";
final String methodName = "hello";
final String action = namespace + methodName;
if(v.getId() == submit_btn.getId()) {
SoapObject so = new SoapObject(namespace, methodName);
so.addProperty("name", "Arjun");
SoapSerializationEnvelope sse = new SoapSerializationEnvelope(SoapEnvelope.VER11);
sse.setOutputSoapObject(so);
HttpTransportSE hse = new HttpTransportSE(url);
try {
hse.call(action, sse);
SoapPrimitive primitive = (SoapPrimitive)sse.getResponse();
Toast.makeText(getApplicationContext(),primitive.toString() , Toast.LENGTH_SHORT);
} catch(IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
以下是我的 Java 代码:
@WebService(serviceName = "PracticeWebServices")
public class PracticeWebServices {
@WebMethod(operationName = "hello")
public String hello(@WebParam(name = "name") String name) {
return "Hello " + name + " !";
}
}
我在 list 文件中包含了互联网权限....
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
现在,当我在 Eclipse 提供的模拟器中运行该文件时。单击按钮时,它会显示一条消息 Unfortunately the program has stopped
当我检查 logCat 时....似乎我在 android.os.NetworkOnMainThreadException
遇到异常最佳答案
您应该将长时间的网络获取操作放在 Thread
或 AsyncTask
中
我建议你使用AsyncTask
你可以通过创建一个 extends AsyncTask
的 class
来做这样的事情
private class LongNetworkOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
SoapObject so = new SoapObject(namespace, methodName);
so.addProperty("name", "Arjun");
SoapSerializationEnvelope sse = new SoapSerializationEnvelope(SoapEnvelope.VER11);
sse.setOutputSoapObject(so);
HttpTransportSE hse = new HttpTransportSE(url);
try {
hse.call(action, sse);
SoapPrimitive primitive = (SoapPrimitive)sse.getResponse();
Toast.makeText(getApplicationContext(),primitive.toString() , Toast.LENGTH_SHORT);
} catch(IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
你可以像这样在你的onClick()
上调用它
@Override
public void onClick(View v) {
if(v.getId()==submit_btn.getId()) {
new LongNetworkOperation.execute();
}
}
此外,我建议您在 onPreExecute()
上显示一个 ProgressDialog
并将其隐藏在 onPostExecute()
中,以便用户知道强烈推荐用于长时间操作的长后台进程
关于java - 从 android 调用 java webservices,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14343585/