在对如何操作感到困惑之后(如 here 和 here 所示),我现在使用以下代码成功连接到我的服务器应用程序和适当的 RESTful 方法:
public void onFetchBtnClicked(View v){
if(v.getId() == R.id.FetchBtn){
Toast.makeText(getApplicationContext(), "You mashed the button, dude.", Toast.LENGTH_SHORT).show();
new CallAPI().execute("http://10.0.2.2:28642/api/Departments/GetCount?serialNum=4242");
}
}
public static class CallAPI extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
String urlString=params[0]; // URL to call
String resultToDisplay = "";
InputStream in = null;
// HTTP Get
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
} catch (Exception e ) {
System.out.println(e.getMessage());
return e.getMessage();
}
return resultToDisplay;
}
protected void onPostExecute(String result) {
Log.i("FromOnPostExecute", result);
}
} // end CallAPI
我意识到我需要为 resultToDisplay 分配一些东西(除了初始化时的空字符串),但是什么?我需要访问/隐藏字符串的“in”的哪一部分?
更新
“手动”方式对我有用,但是 fancypants apache io utils“没那么多”(好吧,它编译...)。这是我的代码:
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
resultToDisplay = getStringFromInputStream(in);
total = IOUtils.toString(in);
resultToDisplay 的作业有效(我得到,“18”)。 total 的分配没有(我得到,“”)。
注意:“getStringFromInputStream()”方法来自 Raghunandan 的链接。
更新 2
这很有效(使用 WIllJBD 的想法来使用 apache commons 的 IOUtils):
new CallWebAPI().execute("http://10.0.2.2:28642/api/Departments/GetCount?serialNum=4242");
. . .
private class CallWebAPI extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
String urlString=params[0]; // URL to call
String result = "";
// HTTP Get
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection =
(HttpURLConnection)url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
if (null != inputStream)
result= IOUtils.toString(inputStream);
} catch (Exception e ) {
System.out.println(e.getMessage());
return e.getMessage();
}
return result;
}
@Override
protected void onPostExecute(String result) {
Log.i("RenameTheWashingtonFootballTeamTheRedskinPeanuts", result);
}
}
...所以显然没有必要在 build.gradle 的依赖项部分添加任何类似“编译文件('libs/commons-io-2.4.jar')”的东西,因为看起来至少是必要的一次,根据 this .如果有人可以验证不再需要对 build.gradle 的 [m,pp] 结尾,我会很高兴。
更新 4
我只是注意到我无意中从 onPostExecute() 方法中删除了“@Override”,但这没有任何区别 - 没有它它工作正常,并且一旦我恢复它就可以正常工作。那么[不]拥有它有什么好处 - 它只是多余的绒毛吗?
最佳答案
为什么不使用像 IOUtils 这样的东西呢?
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null)
String content = IOUtils.toString(inputStream);
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html
现在您可以使用众多库之一将字符串解析为 Json 或 XML。
关于java - 如何访问 Android 中 Web API 方法的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22818292/