我在asp.net上创建了一个web服务,方法如下:
[WebMethod]
public string getUser(string usr)
{
var json = "";
var user = from result in dc.Persons
where result.username == usr
select result.password;
JavaScriptSerializer jss = new JavaScriptSerializer();
json = jss.Serialize(user);
return json;
}
它从指定的用户返回passowrd。
但是如何在我的Android应用程序中使用此方法?
说我想获取用户的密码:Rambo?
答案 0 :(得分:0)
通常我们在使用GET / Post时使用REST webservice。使用Volley这个网有很多例子如何使用它。这是我最喜欢的: Tutorial for Volley
Example.URL: http://DomainOrIpAdress/Accounts/getPassword?user=Rambo <- this is GET Request OR
http://DomainOrIpAdress/Accounts/getPassword <- this is POST Request
教程展示了如何获得返回json的响应,然后你必须使用JsonObjectRequest。这就是我多次这样做的原因。
答案 1 :(得分:0)
在Android中,您需要使用AnyncTask在这样的后台运行httpget调用。
private final String API_URL = "www.example.com/api/{YourControllerName}/getUser?usr="
private class HttpGetter extends AsyncTask<URL, Void, Void> {
@Override
protected Void doInBackground(arg... args) {
// TODO Auto-generated method stub
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(API_URL + arg[0]);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Log.v("Getter", "Your data: " + builder.toString()); //response data
} else {
Log.e("Getter", "Failed");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
HttpGetter get = new HttpGetter();
get.execute("Rambo");