我实际上是使用W3School的WebService进行测试,我有这种方法:
public static float getCelsius(int Fahrenheit)
{
String SOAP_ACTION = "http://www.w3schools.com/xml/FahrenheitToCelsius";
String METHOD_NAME = "FahrenheitToCelsius";
String NAMESPACE = "http://www.w3schools.com/xml/";
String URL = "http://www.w3schools.com/xml/tempconvert.asmx";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("Fahrenheit", Fahrenheit);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
try {
HttpTransportSE transport = new HttpTransportSE(URL);
transport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
return Float.parseFloat(result.toString());
} catch(Exception e) {
return 0;
}
}
但它不起作用,总是返回0。
我在AndroidManifest.xml
中设置了互联网权限,如下所示:
<uses-permission android:name="android.permission.INTERNET" />
我使用AVD模拟器,但我也试过在平板电脑上运行应用程序:没有用。
有任何帮助吗? 抱歉英语不好,希望你能理解。
答案 0 :(得分:1)
以下是解决方案:
您无法在主线程上运行此代码,您必须创建另一个这样的线程:
Thread thread = new Thread() {
@Override
public void run() {
String SOAP_ACTION = "http://www.w3schools.com/xml/FahrenheitToCelsius";
String METHOD_NAME = "FahrenheitToCelsius";
String NAMESPACE = "http://www.w3schools.com/xml/";
String URL = "http://www.w3schools.com/xml/tempconvert.asmx";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("Fahrenheit", "10");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
try {
HttpTransportSE transport = new HttpTransportSE(URL);
transport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
} catch (Exception e) {
Log.e("TESTS", "KSOAP2", e);
}
}
};
thread.start();
无论如何,谢谢你的答案。
答案 1 :(得分:0)
public static float getCelsius(int Fahrenheit) {
String Result = null;
try {
String SOAP_ACTION = "http://www.w3schools.com/xml/FahrenheitToCelsius";
String METHOD_NAME = "FahrenheitToCelsius";
String NAMESPACE = "http://www.w3schools.com/xml/";
String URL = "http://www.w3schools.com/xml/tempconvert.asmx";
SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
request.addProperty("Fahrenheit", Fahrenheit);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(NAMESPACE+ "FahrenheitToCelsius", envelope);
} catch (IOException | XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SoapPrimitive response;
try
{
response = (SoapPrimitive) envelope.getResponse();
Result = response.toString();
}
catch (Exception e)
{
// Helper.warning("Error","Error 2"+e.toString(), this);
}
}
catch (Exception er) {
// Helper.warning("Error","Error 2"+er.toString(), this);
}
return Float.parseFloat(Result);
}
试试上面的代码。