将Android Web服务连接到localhost

时间:2013-12-26 13:08:34

标签: android web-services localhost

我正在与这个特殊的事情作斗争,但无法解决它..请帮助我...... 我正在尝试将android程序连接到在apache服务器上运行的本地主机。

我在互联网上找到了直接连接到自己网站的例子。因此,他们使用名称空间给出名称空间(在下面的程序中)。 但是,由于我的本地主机中有我的Web应用程序,我应该提到什么?

(我在这里粘贴我的代码) MainActivity.java

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

    private String METHOD_NAME = "sum"; // our webservice method name
    private String NAMESPACE = "http://calculator.backend.web.org&#8221"; //I have to give the name space here I guess
    private String SOAP_ACTION = NAMESPACE + METHOD_NAME; 
    private static final String URL = "http://localhost:8081/Test/services/Caluclate?wsdl"; 

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView tv = (TextView) findViewById(R.id.txtAddition);
    try
    {
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        request.addProperty("i", 5);
        request.addProperty("j", 15);
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
        androidHttpTransport.call(SOAP_ACTION,envelope);
        Object result = envelope.getResponse();
        System.out.println(" Result : "  + result.toString());
        ((TextView) findViewById (R.id.txtAddition)).setText("Addition : "+result.toString());
        } catch (Exception E) {
            E.printStackTrace();
            ((TextView) findViewById (R.id.txtAddition)).setText("Error: "   + E.getClass().getName() + ":" + E.getMessage());
        }
    }
}

Calculate.java(网络应用中的程序)

public class Caluclate {
    public int sum() {
         return (1);
   }
   public int subtract(int i, int j) {
         return (i - j);
   }
   public int multiply(int i, int j) {
         return (i * j);
   }
   public int divide(int i, int j) {
         return (i / j);
   }
}

感谢您帮助我...

3 个答案:

答案 0 :(得分:1)

我假设服务端点在远程计算机上运行,​​但不是直接在移动设备上运行。

在这种情况下,localhost将无法工作,因为它是127.0.0.1的本地别名,它解析为自身。

在您的代码中,每个设备都会尝试访问自己托管的服务。您必须通过托管端点的服务器的IP替换localhost

答案 1 :(得分:1)

您可以使用:

private static final String URL = "http:// 10.0.2.2:8081/Test/services/Caluclate?wsdl"; 

答案 2 :(得分:0)

朋友找到你的PC分配IP(转到CMD并输入ipconfig并找到IP地址)替换" Localhost"使用该IP地址。这对我有用。