GAE/JではHttpClientは使えないっぽい
smart.fm(旧iKnow!)のWEB APIを使ったアプリケーションを作ろうとして、WEB APIの実行部分をcommons HTTP Clientを使ってやってみたんですが、ローカル環境ではうまく動かず。
java.security.AccessControlException: access denied (java.net.SocketPermission api.iknow.co.jp resolve)
色々調べてたんだけどよく分からなかったので、とりあえずデプロイして確認してみた。やっぱりエラー発生。でもローカルとは違うエラー。
java.lang.NoClassDefFoundError: java.net.Socket is a restricted class. Please see the Google App Engine developer's guide for more details.
確かにhttp://code.google.com/intl/ja/appengine/docs/java/jrewhitelist.htmlを確認すると、java.net.Socketは無い。あらら。。
ソースコード
動かなかったプログラムはこんなの。
String result = ""; HttpClient client = new HttpClient(); HttpMethod method = new GetMethod("http://api.iknow.co.jp/items/matching/record.xml?per_page=5"); try { client.executeMethod(method); result += method.getResponseBodyAsString(); } catch (Exception e) { e.printStackTrace(); } finally { method.releaseConnection(); }
で、HTTP Clientを使わないで作ったのがこれ。
String result = ""; BufferedReader in = null; HttpURLConnection con = null; try { URL url = new URL("http://api.iknow.co.jp/items/matching/record.xml?per_page=5"); con = (HttpURLConnection) url.openConnection(); con.setRequestProperty("Content-type", "text/xml"); con.setRequestMethod("GET"); con.setConnectTimeout(60000); in = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) in.close(); if (con != null) con.disconnect(); }
こっちだとエラーは出なくなったんだけど、ブラウザで実行した時の結果とは明らかに違うものが取得されているんだよな。。うーむ、なんなんだろう。
勘違いでした。デバッグしたらうまくいってた。表示ロジックにミスがあっただけでした!(2009/4/21追記)