在Android中调用Web API并接收返回值 [英] Calling web API and Receive return value in Android
问题描述
我在谷歌上搜索了这些主题,但没有得到任何有用的信息.
I've googled for that topics and don't get any useful information.
我想在我的 android 项目中使用 Web API,但不知道如何从 android 或 java 调用它们
I want to use Web API in my android projects, but don't know how to call them from android or java
我从 this 站点获得了一些 WEB API,想在我的 android 项目中使用.例如,一个 web api URL :/api/uname2uid/{uname}.
I've got some WEB API from this site and want to use in my android project.
For example, a web api URL : /api/uname2uid/{uname}.
将用户名转换为用户数字ID
我想将从该 API 返回的用户 ID 显示到 TextView
中.所以我需要返回值作为字符串或数字.请帮帮我.
I want to display the User ID returned from that API into a TextView
. So i need the return value as string or number. Please help me this.
编辑
我只想学习如何使用 WEB API
为了更简单:在我的程序中,我有一个 TextView
、一个 EditText
和一个 Button
当我按下 Button
时,TextView
将根据 EditText<中给出的 用户名 的相应用户 ID 更新/code> 字段就是这样.一个有效的例子对我理解这一点很有帮助.
EDIT
I just want to learn how to use WEB API
For more simplicity:
In my program I have a TextView
, aEditText
and a Button
When i press the Button
then TextView
will update by corresponding user ID for Username given in EditText
field thats all. An working example will be great for me to understanding this.
推荐答案
由于我只想显示从 API 返回的用户 ID,下面的解决方案对我有用.
Since I just want to display the the User ID return from the API, below the solution is work for me.
public class MainActivity extends Activity {
public static TextView txtUserid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnUserid = (Button) findViewById(R.id.btnUserid);
btnUserid.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new UserNameToId().execute("https://uhunt.onlinejudge.org/api/uname2uid/almaruf");
}
});
}
protected class UserNameToId extends AsyncTask<String, Void, String> {
@Override
public String doInBackground(String... url) {
try {
URL Url = new URL(url[0]);
URLConnection urlConnection = Url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String str = "";
str = bufferedReader.readLine();
return str;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
txtUserid = (TextView) findViewById(R.id.txtUserId);
txtUserid.setText(result);
}
}
}
这篇关于在Android中调用Web API并接收返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!