在对如何做到这一点感到困惑之后(可以看出here https://stackoverflow.com/questions/22797194/how-to-call-a-restful-method-from-android and here https://stackoverflow.com/questions/22798949/why-is-my-web-api-server-refusing-to-accept-calls-from-android,我现在使用以下代码成功连接到我的服务器应用程序和适当的 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”的哪一部分为字符串?
UPDATE
“手动”方式对我有用,但 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”)。总计的分配没有(我得到,“”)。
Note:“getStringFromInputStream()”方法来自 Raghunandan 的链接。
UPDATE 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);
}
}
...所以显然没有必要将“编译文件('libs/commons-io-2.4.jar')”之类的内容添加到 build.gradle 的依赖项部分,因为看起来至少有一次是必要的,根据this http://www.codeproject.com/Tips/607552/How-to-add-external-library-file-in-Android-Studio。如果有人可以验证不再需要对 build.gradle 的此类修改,我会很高兴。
UPDATE 4
我只是注意到我无意中从 onPostExecute() 方法中删除了“@Override”,但这没有什么区别 - 没有它它工作得很好,一旦我恢复它它工作得很好。那么,不拥有它有什么好处——它只是多余的东西吗?