[英]How to use WebService in Android?
I have made a webservice in asp.net, the method looks like this: 我在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;
}
It returns the passowrd from the specified user. 它从指定的用户返回密码。
However how can I use this method in my android app ? 但是,如何在我的android应用程序中使用此方法?
Say that I wanted to get the password for user: Rambo ? 说我想获取用户密码:Rambo?
Well for this usually we use REST webservice with using GET/Post. 为此,通常我们将REST Web服务与GET / Post一起使用。 Use Volley for this the net has many examples how to use it. 为此使用Volley,网络上有许多使用它的示例。 this is my favorite: Tutorial for Volley 这是我的最爱: Volley教程
Example.URL: http://DomainOrIpAdress/Accounts/getPassword?user=Rambo <- this is GET Request OR
http://DomainOrIpAdress/Accounts/getPassword <- this is POST Request
And the tutorial shows how to get the response you return a json then you have to use JsonObjectRequest. 本教程显示如何获取返回json的响应,然后必须使用JsonObjectRequest。 Well this is how I done it many many times. 好吧,这就是我很多次这样做的方式。
In Android, you need to use AnyncTask to run the httpget call in background like this. 在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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.