Android から単純な REST メソッドを呼び出す 2 つの異なる方法を試しました。上記の REST メソッド (他のクライアントから機能する) は、単に 17 などの int val を返します。
次の試みはどちらも、私がオンラインで見つけたコードに基づいています。1つは次のようになります。
public void onFetchBtnClicked(View v){ if(v.getId() == R.id.FetchBtn){ Toast.makeText(getApplicationContext(), "ボタンをつぶしてしまいました.", Toast.LENGTH_SHORT).show() ; new NetworkTask().execute(); } }
public static class NetworkTask extends AsyncTask {
@Override
protected String doInBackground(Void... params) {
final String TAG;
TAG = "callWebService";
String deviceId = "Android Device";
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet("http://localhost:28642/api/Departments/GetCount");
request.addHeader("deviceId", deviceId);
ResponseHandler<String> handler = new BasicResponseHandler();
String result = "";
try
{
result = httpclient.execute(request, handler);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
Log.e(TAG, "ClientProtocolException in callWebService(). " + e.getMessage());
}
catch (IOException e)
{
e.printStackTrace();
Log.e(TAG, "IOException in callWebService(). " + e.getMessage());
}
httpclient.getConnectionManager().shutdown();
Log.i(TAG, "**callWebService() successful. Result: **");
Log.i(TAG, result);
Log.i(TAG, "*****************************************");
return result;
}
@Override
protected void onPostExecute(String result) {
final String TAG;
TAG = "onPostExecute";
if (null != result)
Log.i(タグ、結果); }
上記のコードでは、次のコード行が失敗した後:
result = httpclient.execute(request, handler) ;
...わかりました、「*E/callWebService﹕ IOException in callWebService(). Connection to http://localhost:28642 refused*
」
Mednieks、Dornin、Meike、および Nakamura による O'Reilly の「Programming Android」の本でこれを読んだように、この問題はスレッドの問題である可能性があります。別のスレッドで実行されます! 別のスレッドから見える状態を書き込んだり、別のスレッドから書き込み可能な状態を読み取ったりしてはなりません.これにはそのパラメータが含まれます."
私の他の試みで:
public void onFetchBtnClicked(View v){
if(v.getId() == R.id.FetchBtn){
Toast.makeText(getApplicationContext(), "You mashed the button, dude.", Toast.LENGTH_SHORT).show();
callWebService("http://localhost:28642/api/Departments/GetCount");
}
}
public String callWebService(String requestUrl)
{
final String TAG;
TAG = "callWebService";
String deviceId = "Android Device";
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(requestUrl);
request.addHeader("deviceId", deviceId);
ResponseHandler<String> handler = new BasicResponseHandler();
String result = "";
try
{
result = httpclient.execute(request, handler);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
Log.e(TAG, "ClientProtocolException in callWebService(). " + e.getMessage());
}
catch (IOException e)
{
e.printStackTrace();
Log.e(TAG, "IOException in callWebService(). " + e.getMessage());
}
httpclient.getConnectionManager().shutdown();
Log.i(TAG, "**callWebService() successful. Result: **");
Log.i(TAG, result);
Log.i(TAG, "*****************************************");
return result;
}
...デバッガーは、同じ問題行にヒットした後、View.class にダンプします (result = httpclient.execute(request, handler))。なぜそうなるのかはわかりません*が、logcatのエラーメッセージで示されているように、問題の核心は次のとおりだと思います:「原因:android.os.NetworkOnMainThreadException」
※UI(ビュー)スレッド内で何か不都合なことが試みられているためかもしれません。
また (大したことではありませんが、おそらく「興味深い」): Toast の後にメソッド呼び出しが行われたときに、Toast がポップアップしません (それ以外の場合は機能します)。
(Web API) サーバーには、対応する Controller メソッドにブレークポイントが設定されていますが、到達することはありません。前述のように、サーバーは実行中であり、他の (Windows アプリ) クライアントに問題なく応答します。
Android から RESTful メソッドを呼び出す簡単な方法が必要です。しかし、何を/どのように?
アップデート
私もこれを試してみましたが、次のように呼び出します。
RestClient client = new RestClient("http://localhost:28642/api/Departments/GetCount");
try {
client.Execute(RestClient.RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
Log.i("CZECH_THIS", response);
...しかし、「NetworkOnMainThread」例外をスローしても問題ありません。
更新 2
今までで一番近かったと思います。この場合、サーバーが原因である可能性があります。これは、次のコードが原因です。
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://localhost:28642/api/Departments/GetCount");
}
}
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
....スローされる例外は次のとおりです。
libcore.io.ErrnoException: 接続に失敗しました: ECONNREFUSED (接続が拒否されました) localhost/127.0.0.1 (ポート 28642) への接続に失敗しました: 接続に失敗しました: ECONNREFUSED (接続が拒否されました)
...そして、Android アプリは引き続き実行されます (他の例では失敗します)。
サーバーが接続を拒否するのはなぜですか?
更新 3
私はそれを持っていると一瞬思いました: URL でシリアル番号を渡すのを忘れていました. しかし、そうしても失敗します。
サーバー アプリのコントローラー メソッドにブレークポイントがあります。また、Repository メソッドでも、それらに到達することはありません。
何が間違っている可能性がありますか?
「localhost」は (URL で) 使用するのが間違っていますか? 代わりにコンピュータの名前を使用する必要がありますか?
URL (文字どおり " http://localhost:28642/api/Departments/GetCount?serialNum=4242
" として渡される) を逐語化する必要がありますか?
更新 4
「locohost」をマシン名に変更すると、「ホスト名に関連付けられたアドレスがありません」と表示されるので問題ありません...
奇妙なことに、この行は問題なく実行されます。
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
...これは、例外がスロー/キャッチされる前の最後の行です。
in = new BufferedInputStream(urlConnection.getInputStream());
しかし、これを見ると、おそらく私は自分の強打から逃れる必要があります。しかし、"http:" の後のように、既に 2 回叩いている場合、3 回叩く必要があるのでしょうか? それとも4倍強打?きっとシーリングワックスじゃない…?