如何从Android中的Web服务获取数据?

时间:2013-07-18 05:48:03

标签: android json web-services soap

我是Android开发的新手,我正在开发一个可以从Web服务获取数据的应用程序。例如,我在我的Android应用程序上创建了一个登录名,将要输入的数据来自Web服务。我怎么能这样做,使用JSON或SOAP最简单的方法是什么?请提供一些示例,以便我知道如何做到这一点,谢谢。

3 个答案:

答案 0 :(得分:3)

这是一个很好的例子,我使用类似的东西: enter link description here

private final String NAMESPACE = "http://tempuri.org/";
private final String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";
private final String SOAP_ACTION = "http://tempuri.org/CelsiusToFahrenheit";
private final String METHOD_NAME = "CelsiusToFahrenheit";

public void getFahrenheit(String celsius) {
//Create request
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//Property which holds input parameters
PropertyInfo celsiusPI = new PropertyInfo();
//Set Name
celsiusPI.setName("Celsius");
//Set Value
celsiusPI.setValue(celsius);
//Set dataType
celsiusPI.setType(double.class);
//Add the property to request object
request.addProperty(celsiusPI);
//Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
        SoapEnvelope.VER11);
envelope.dotNet = true;
//Set output SOAP object
envelope.setOutputSoapObject(request);
//Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

try {
    //Invole web service
    androidHttpTransport.call(SOAP_ACTION, envelope);
    //Get the response
    SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
    //Assign it to fahren static variable
    fahren = response.toString();

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

}

答案 1 :(得分:3)

对于JSON,请检查此tutorial。 对于SOAP检查this

答案 2 :(得分:0)

Json是最简单,最干净的通信协议。我建议使用库来获取数据https://github.com/kodart/Httpzoid

有一些使用样本。