Androidな方なので,久しぶりにandroidのコードを作成。
なるべくリアルタイムに近いレートを使いたいとのことなので,
いいAPIがネットに転がってないか検索したところ,
さすがGoogle先生!パラメータをわたすと計算して返してくれるという優れものを発見。
http://www.google.com/ig/calculator?hl=en&q=1USD=?JPY
のように,httpのgetでパラメータをおくると下記のような結果が返ってくる。
{lhs: "1 U.S. dollar",rhs: "77.9787898 Japanese yen",error: "",icc: true}
これをJSONなりで処理すれば,良い感じに扱えるはず。
ということでコードです。
String uri = "http://www.google.com/ig/calculator?hl=en&q=1USD=?JPY"; HttpClient httpClient = new DefaultHttpClient(); HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, 1000); HttpConnectionParams.setSoTimeout(params, 1000); HttpUriRequest httpRequest = new HttpGet(uri); HttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpRequest); } catch (ClientProtocolException e) { //例外処理 return; } catch (IOException e){ //例外処理 return; } String json = null; if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ HttpEntity httpEntity = httpResponse.getEntity(); try { json = EntityUtils.toString(httpEntity); } catch (ParseException e) { //例外処理 return; } catch (IOException e) { //例外処理 return; } finally { try { httpEntity.consumeContent(); } catch (IOException e) { //例外処理 return; } } } httpClient.getConnectionManager().shutdown(); String result = ""; try { JSONObject rootObject = new JSONObject(json); result = rootObject.getString("rhs"); } catch (JSONException e){ //例外処理 return; }
以上のように,
リクエスト作成→レスポンス受信→JSONオブジェクトに格納→結果用Stringオブジェクトに変換
こんな感じでいけました。
実際につくったアプリも公開していますので,Google PlayでProject Betcheのアプリ,ExchangeATConverterを検索してみてください。
0 件のコメント:
コメントを投稿