如何从android轻松调用网络Web服务?

时间:2011-11-06 13:46:16

标签: android

我需要从android进行一些简单的Web服务调用。 我知道服务器的IP地址 - 我知道我需要调用的方法是什么。 服务器基于.net平台 - 我需要调用的方法将返回给我简单的字符串,告诉我什么是服务器Web服务版本。

我不知道怎么打这个电话。

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

答案取决于这是什么类型的Web服务...... SOAP(XML)Web服务需要一些XML功能,最简单的选择是使用库(参见下面的KSOAP2)...... REST Web服务可能适用于纯HTTP(也许加上JSON)......

有关如何从Android调用Web服务的所有提及选项的示例源代码/演练/库/ doc,请参阅:

答案 1 :(得分:1)

public class SOAPActivity extends Activity {
     private final String NAMESPACE = "http://www.webserviceX.NET/";
        private final String URL = "http://www.webservicex.net/ConvertWeight.asmx";
        private final String SOAP_ACTION = "http://www.webserviceX.NET/ConvertWeight";
        private final String METHOD_NAME = "ConvertWeight";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        SoapObject soapObject=new SoapObject(NAMESPACE, METHOD_NAME);

        String weight = "700";
        String fromUnit = "Kilograms";
        String toUnit = "Grams";

        PropertyInfo weightProp =new PropertyInfo();
        weightProp.setName("Weight");
        weightProp.setValue(weight);
        weightProp.setType(double.class);
        soapObject.addProperty(weightProp);

        PropertyInfo fromProp =new PropertyInfo();
        fromProp.setName("FromUnit");
        fromProp.setValue(fromUnit);
        fromProp.setType(String.class);
        soapObject.addProperty(fromProp);

        PropertyInfo toProp =new PropertyInfo();
        toProp.setName("ToUnit");
        toProp.setValue(toUnit);
        toProp.setType(String.class);
        soapObject.addProperty(toProp);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(soapObject);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

        try {
            androidHttpTransport.call(SOAP_ACTION, envelope);
            SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
            Log.i("myApp", response.toString());

            TextView tv = new TextView(this);
            tv.setText(weight+" "+fromUnit+" equal "+response.toString()+ " "+toUnit);
            setContentView(tv);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    }

这是SOAP Web服务的代码。