JSONFunctions.getJSONfromURL

随分前に自分用に作って持ってたのですが、こないだ云々したナニでサーバサイドから戻ってくるのが JSON ってことで流用してみました。以下で管理してます。

基本的にはライブラリプロジェクトの形になっているので、Eclipse なプロジェクトにすれば bin だったかに jar ができるのでそれを呼び出し元なプロジェクトに持っていって Build Path を通してあげれば OK のはず。

今回

中身があまりにも微妙だったのと HttpResponse なオブジェクトを適切に扱う例を目にしたので手を入れてみました。修正後の手続き定義が以下。

    public static JSONObject getJSONfromURL(String url, DefaultHttpClient httpclient)
        throws IOException, ClientProtocolException, RuntimeException, JSONException {
        InputStream is = null;
        
        HttpGet httpget = new HttpGet(url);
        is = httpclient.execute(httpget,
                new ResponseHandler<InputStream>() {

                    @Override
                    public InputStream handleResponse(HttpResponse response)
                            throws ClientProtocolException, IOException {
                        switch (response.getStatusLine().getStatusCode()) {
                        case HttpStatus.SC_OK:
                            return response.getEntity().getContent();
                        default:
                            throw new RuntimeException("");
                        }
                    }
        });

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        
        return new JSONObject(sb.toString());            
    }

基本的に HttpResponse 型なオブジェクトの後始末を楽に済ませたいのであれば、上記な形の execute を使うのが楽らしいです。
今回、POST な通信もあったので、こちらに機能を盛り込めば良かったのですが、そこまでもごもごする余裕が無かったスね。もし盛り込めれば別途盛り込んでみたいと思います。

とりあえず

レスポンスな Status が 200 以外の場合に RuntimeException 投げてますが中身が空なのでここだけ修正して push の方向。HttpResponse#getStatusLine().getStatusCode の戻りは int 型らしいので、以下で良いかな。良いよね。

                        default:
                            throw new RuntimeException("HTTP Status is " + 
			    	  response.getStatusLine().getStatusCode());
                        }

大丈夫だろうか (を