Consuming a web service in an android application in localhost

自作多情 提交于 2019-12-04 13:02:47

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...

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

Squonk

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.

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...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!