タケユー・ウェブ日報

Ruby on Rails や Flutter といったWeb・モバイルアプリ技術を武器にお客様のビジネス立ち上げを支援する、タケユー・ウェブ株式会社の技術ブログです。

AndroidアプリでWebAPIにデータをPOSTして結果を取得するには

AsyncTaskLoaderHttpPostリクエス

こちらの記事を参考に作成したLoaderに、POST送信機能を実装してみた。

public class HttpAsyncLoader extends AsyncTaskLoader<String> {
    private HttpUriRequest request = null;
    public HttpAsyncLoader(Context context, String url) {
        super(context);
        this.request = new HttpGet(url);
    }
    public HttpAsyncLoader(Context context, String url, List<NameValuePair> postData) {
        super(context);
        HttpPost request = new HttpPost(url);
        try {
            request.setEntity(new UrlEncodedFormEntity(postData, "UTF-8"));
            this.request = request;
        } catch(UnsupportedEncodingException e) {
            Log.e(this.getClass().getSimpleName(), e.getMessage());
        }
    }

    @Override
    public String loadInBackground() {
        HttpClient httpClient = new DefaultHttpClient();
        try {
            String responseBody = httpClient.execute(request,
                    new ResponseHandler<String>() {
                        @Override
                        public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
                            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                                return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
                            }
                            return null;
                        }
                    });
            return responseBody;
        }
        catch(Exception e) {
            Log.e(this.getClass().getSimpleName(), e.getMessage());
        }
        finally {
            httpClient.getConnectionManager().shutdown();
        }
        return null;
    }
}

使ってみた:MovableType DataAPIでアクセストークンを取得する例