在本地主机的 Android 应用程序中使用 Web 服务

发布于 2024-10-07 12:25:34 字数 546 浏览 0 评论 0原文

我正在尝试使用我从 Android 应用程序本地创建的 Web 服务。 我的问题是,在我的 Android 应用程序中,在某个时刻,我必须提供一个带有如下所示参数的 URL: http://localhost:8080/CalculatorApp/CalculatorWSService/add?i=1&j=1

其中 CalculatorWS 是我使用的 Web 服务其中,add是其中的操作,ijadd操作的参数。目前,我正在使用示例应用程序计算器(来自 NetBeans)进行测试,我想检索正确的 URL 以提供给我的 Web 服务客户端(Android 应用程序),以便它可以返回一个要解析的 XML。

我尝试使用上面提到的 URL,但它不起作用。

有人知道正确的网址是什么吗?

I am trying to consume a web service that I created locally from an Android application.
My problem is that in my Android app, at a certain point, I have to give an URL with parameters that looks like this : http://localhost:8080/CalculatorApp/CalculatorWSService/add?i=1&j=1

where CalculatorWS is the web service I use, add is the operation in it and i and j are parameters of add operation. For now I am using a sample app Calculator (from NetBeans) for testing and I want to retrieve the correct URL to give to my web service client (Android app) so it can give me back an XML to parse.

I tried to use that URL mentioned above but it doesn't work.

Does anybody know what is the correct URL to put ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

韬韬不绝 2024-10-14 12:25:34

您需要将 URL 设置为 10.0.2.2:portNr

portNr = ASP.NET 开发服务器给定的端口
我当前的服务正在运行
localhost:3229/Service.svc

所以我的网址是 10.0.2.2:3229

我用这种方式解决了我的问题

,希望它有帮助...

you need to set URL as 10.0.2.2:portNr

portNr = the given port by ASP.NET Development Server
my current service is running on
localhost:3229/Service.svc

so my url is 10.0.2.2:3229

i'd fixed my problem this way

i hope it helps...

素罗衫 2024-10-14 12:25:34

使用此 URL:

http://10.0.2.2:8080/CalculatorApp /CalculatorWSService/add?i=1&j=1

由于 Android 模拟器在虚拟机上运行,​​因此我们必须使用此 IP 地址而不是 localhost 或 127.0.0.1

Use this URL:

http://10.0.2.2:8080/CalculatorApp/CalculatorWSService/add?i=1&j=1

Since Android emulator run on Virtual Machine therefore we have to use this IP address instead of localhost or 127.0.0.1

朦胧时间 2024-10-14 12:25:34

如果您使用的是模拟器,请阅读以下段落: Referring to localhost来自模拟环境

如果你需要引用你的主机的localhost,比如当
您希望模拟器客户端联系在同一服务器上运行的服务器
host,使用别名10.0.2.2来指代主机的环回
界面。从模拟器的角度来看,localhost (127.0.0.1)
指的是它自己的环回接口。

If you're using an emulator then read below paragraph taken from: Referring to localhost from the emulated environment

If you need to refer to your host computer's localhost, such as when
you want the emulator client to contact a server running on the same
host, use the alias 10.0.2.2 to refer to the host computer's loopback
interface. From the emulator's perspective, localhost (127.0.0.1)
refers to its own loopback interface.

梓梦 2024-10-14 12:25:34

sharktiger 就像你在评论中所说的那样,我将在这里粘贴一些代码来帮助你弄清楚如何进行,此代码尝试连接到 Web 服务并解析检索到的 InputStream,就像 @Vikas Patidar 和 @MisterSquonk 说的那样,你必须像他们解释的那样在 android 代码中配置 url。因此,我发布了我的代码

和调用 HttpUtils 的示例...

public static final String WS_BASE = "http://www.xxxxxx.com/dev/xxx/";
public static final String WS_STANDARD = WS_BASE + "webserviceoperations.php";
public static final String REQUEST_ENCODING = "iso-8859-1";

    /**
         * Send a request to the servers and retrieve InputStream
         * 
         * @throws AppException
         */
        public static Login logToServer(Login loginData) {
            Login result = new Login();
            try {
                // 1. Build XML
                byte[] xml = LoginDAO.generateXML(loginData);
                // 2. Connect to server and retrieve data
                InputStream is = HTTPUtils.readHTTPContents(WS_STANDARD, "POST", xml, REQUEST_ENCODING, null);
                // 3. Parse and get Bean
                result = LoginDAO.getFromXML(is, loginData);
            } catch (Exception e) {
                result.setStatus(new ConnectionStatus(GenericDAO.STATUS_ERROR, MessageConstants.MSG_ERROR_CONNECTION_UNKNOWN));

            }
            return result;
        }

以及我的类 HTTPUtils 中的方法 readHTTPContents

/**
     * Get the InputStream contents for a specific URL request, with parameters.
     * Uses POST. PLEASE NOTE: You should NOT use this method in the main
     * thread.
     * 
     * @param url
     *            is the URL to query
     * @param parameters
     *            is a Vector with instances of String containing the parameters
     */
    public static InputStream readHTTPContents(String url, String requestMethod, byte[] bodyData, String bodyEncoding, Map<String, String> parameters)
            throws AppException {
        HttpURLConnection connection = null;
        InputStream is = null;
        try {
            URL urlObj = new URL(url);
            if (urlObj.getProtocol().toLowerCase().equals("https")) {
                trustAllHosts();
                HttpsURLConnection https = (HttpsURLConnection) urlObj
                        .openConnection();
                https.setHostnameVerifier(new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });
                connection = https;
            } else {
                connection = (HttpURLConnection) urlObj.openConnection();
            }
            // Allow input
            connection.setDoInput(true);
            // If there's data, prepare to send.
            if (bodyData != null) {
                connection.setDoOutput(true);
            }
            // Write additional parameters if any
            if (parameters != null) {
                Iterator<String> i = parameters.keySet().iterator();
                while (i.hasNext()) {
                    String key = i.next();
                    connection.addRequestProperty(key, parameters.get(key));
                }
            }
            // Sets request method
            connection.setRequestMethod(requestMethod);
            // Establish connection
            connection.connect();
            // Send data if any

            if (bodyData != null) {
                OutputStream os = connection.getOutputStream();
                os.write(bodyData);
            }
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new AppException("Error HTTP code " + connection.getResponseCode());
            }
            is = connection.getInputStream();
            int numBytes = is.available();
            if (numBytes <= 0) {
                closeInputStream(is);
                connection.disconnect();
                throw new AppException(MessageConstants.MSG_ERROR_CONNECTION_UNKNOWN);
            }

            ByteArrayOutputStream content = new ByteArrayOutputStream();

            // Read response into a buffered stream
            int readBytes = 0;
            while ((readBytes = is.read(sBuffer)) != -1) {
                content.write(sBuffer, 0, readBytes);
            }
            ByteArrayInputStream byteStream = new ByteArrayInputStream(content.toByteArray());
            content.flush();
            return byteStream;
        } catch (Exception e) {
//          Logger.logDebug(e.getMessage());
            throw new AppException(e.getMessage());
        } finally {
            closeInputStream(is);
            closeHttpConnection(connection);
        }
    }

希望这可以帮助您...

sharktiger like you says on the comments, i'll paste here some code to help you to figure how to proced, this code try to connect to a web service and parse the InputStream retrieved, just like @Vikas Patidar and @MisterSquonk says, you must configure the url in the android code like them explain. So, i post my code

and example of call to HttpUtils...

public static final String WS_BASE = "http://www.xxxxxx.com/dev/xxx/";
public static final String WS_STANDARD = WS_BASE + "webserviceoperations.php";
public static final String REQUEST_ENCODING = "iso-8859-1";

    /**
         * Send a request to the servers and retrieve InputStream
         * 
         * @throws AppException
         */
        public static Login logToServer(Login loginData) {
            Login result = new Login();
            try {
                // 1. Build XML
                byte[] xml = LoginDAO.generateXML(loginData);
                // 2. Connect to server and retrieve data
                InputStream is = HTTPUtils.readHTTPContents(WS_STANDARD, "POST", xml, REQUEST_ENCODING, null);
                // 3. Parse and get Bean
                result = LoginDAO.getFromXML(is, loginData);
            } catch (Exception e) {
                result.setStatus(new ConnectionStatus(GenericDAO.STATUS_ERROR, MessageConstants.MSG_ERROR_CONNECTION_UNKNOWN));

            }
            return result;
        }

and the method readHTTPContents from my class HTTPUtils

/**
     * Get the InputStream contents for a specific URL request, with parameters.
     * Uses POST. PLEASE NOTE: You should NOT use this method in the main
     * thread.
     * 
     * @param url
     *            is the URL to query
     * @param parameters
     *            is a Vector with instances of String containing the parameters
     */
    public static InputStream readHTTPContents(String url, String requestMethod, byte[] bodyData, String bodyEncoding, Map<String, String> parameters)
            throws AppException {
        HttpURLConnection connection = null;
        InputStream is = null;
        try {
            URL urlObj = new URL(url);
            if (urlObj.getProtocol().toLowerCase().equals("https")) {
                trustAllHosts();
                HttpsURLConnection https = (HttpsURLConnection) urlObj
                        .openConnection();
                https.setHostnameVerifier(new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });
                connection = https;
            } else {
                connection = (HttpURLConnection) urlObj.openConnection();
            }
            // Allow input
            connection.setDoInput(true);
            // If there's data, prepare to send.
            if (bodyData != null) {
                connection.setDoOutput(true);
            }
            // Write additional parameters if any
            if (parameters != null) {
                Iterator<String> i = parameters.keySet().iterator();
                while (i.hasNext()) {
                    String key = i.next();
                    connection.addRequestProperty(key, parameters.get(key));
                }
            }
            // Sets request method
            connection.setRequestMethod(requestMethod);
            // Establish connection
            connection.connect();
            // Send data if any

            if (bodyData != null) {
                OutputStream os = connection.getOutputStream();
                os.write(bodyData);
            }
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new AppException("Error HTTP code " + connection.getResponseCode());
            }
            is = connection.getInputStream();
            int numBytes = is.available();
            if (numBytes <= 0) {
                closeInputStream(is);
                connection.disconnect();
                throw new AppException(MessageConstants.MSG_ERROR_CONNECTION_UNKNOWN);
            }

            ByteArrayOutputStream content = new ByteArrayOutputStream();

            // Read response into a buffered stream
            int readBytes = 0;
            while ((readBytes = is.read(sBuffer)) != -1) {
                content.write(sBuffer, 0, readBytes);
            }
            ByteArrayInputStream byteStream = new ByteArrayInputStream(content.toByteArray());
            content.flush();
            return byteStream;
        } catch (Exception e) {
//          Logger.logDebug(e.getMessage());
            throw new AppException(e.getMessage());
        } finally {
            closeInputStream(is);
            closeHttpConnection(connection);
        }
    }

Hope this help you...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文