【发布时间】:2014-05-14 03:21:37
【问题描述】:
在对如何做到这一点感到困惑之后(如 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”的哪一部分?
更新
“手动”方式对我有用,但花哨的 apache io 实用程序“没那么多”(嗯,它编译...)。这是我的代码:
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”)。总的分配没有(我得到,“”)。
注意:“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]endments,我会很高兴。
更新 4
我刚刚注意到我无意中从 onPostExecute() 方法中删除了“@Override”,但它没有任何区别 - 没有它它可以正常工作,并且一旦我恢复它就可以正常工作。那么[不]拥有它有什么好处 - 它只是多余的绒毛吗?
【问题讨论】:
-
快速谷歌搜索 bufferedinputstream to string 返回了这个结果,stackoverflow.com/questions/5713857/… 这可能是你的答案。
-
Raghunandan 评论中的代码就像一个手链。
-
要考虑的一件事,我相信一旦您将输入流读取到其末尾,尝试再次读取它不会返回任何内容,因为您处于输入流的末尾。根据输入流,您可能会考虑使用
mark()和reset()将输入流恢复到开头以供重用,如果markSupported() = true;否则您已经消耗了输入流的内容,并且在进一步使用时它将保持为空。
标签: java android android-asynctask http-get bufferedinputstream