问题
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 ?
回答1:
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...
回答2:
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
回答3:
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.
回答4:
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...
来源:https://stackoverflow.com/questions/4456921/consuming-a-web-service-in-an-android-application-in-localhost