/*
 * Copyright 2015 OpenMarket Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.matrix.androidsdk.rest.client;

import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * UrlPostTask triggers a POST with no param.
 */
public class UrlPostTask extends AsyncTask<String, Void, String> {

    public interface IPostTaskListener {
        /**
         * The post succceeds.
         * @param object the object retrieves in the response.
         */
        void onSucceed(JsonObject object);

        /**
         * The post failed
         * @param errorMessage the error message.
         */
        void onError(String errorMessage);
    }

    private static final String LOG_TAG = "UrlPostTask";

    // the post listener
    private IPostTaskListener mListener;

    @Override
    protected String doInBackground(String... params) {
        String result = "";

        try {
            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0]);
            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            HttpEntity entity = response.getEntity();

            if (entity != null) {
                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                result = convertStreamToString(instream);
            }
        } catch(Exception e) {
            // Do something about exceptions
            result = e.getMessage();
        }
        return  result;
    }

    /**
     * Set the post listener
     * @param listener the listener
     */
    public void setListener(IPostTaskListener listener) {
        mListener = listener;
    }

    /**
     * Convert a stream to a string
     * @param is the input stream to convert
     * @return the string
     */
    private static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "convertStreamToString " + e.getLocalizedMessage());
        } finally {
            try {
                is.close();
            } catch (Exception e) {
                Log.e(LOG_TAG, "convertStreamToString finally failed " + e.getLocalizedMessage());
            }
        }
        return sb.toString();
    }

    protected void onPostExecute(String result) {
        JsonObject object = null;

        Log.d(LOG_TAG, "onPostExecute " + result);

        try {
            JsonParser parser = new JsonParser();
            object = parser.parse(result).getAsJsonObject();
        } catch (Exception e) {
            Log.e(LOG_TAG, "## onPostExecute() failed" + e.getMessage());
        }

        if (null != mListener) {
            if (null != object) {
                mListener.onSucceed(object);
            } else {
                mListener.onError(result);
            }
        }
    }
}

@@ -16,9 +16,9 @@
  201
-5
+6
  Ope
@@ -773,217 +773,36 @@
 ort 
-org.apache.http.HttpEntity;%0Aimport org.apache.http.HttpResponse;%0Aimport org.apache.http.client.HttpClient;%0Aimport org.apache.http.client.methods.HttpPost;%0Aimport org.apache.http.impl.client.DefaultHttpClient;%0A
+java.io.BufferedInputStream;
 %0Aimp
@@ -890,16 +890,72 @@
 mReader;
+%0Aimport java.net.HttpURLConnection;%0Aimport java.net.URL;
 %0A%0A/**%0A *
@@ -1154,16 +1154,27 @@
 cceeds.%0A
+         *%0A
         
@@ -1357,27 +1357,8 @@
 sage
- the error message.
 %0A   
@@ -1670,328 +1670,235 @@
     
-// Create a new HttpClient and Post Header%0A            HttpClient httpclient = new DefaultHttpClient();%0A            HttpPost httppost = new HttpPost(params%5B0%5D);%0A            // Execute HTTP Post Request%0A            HttpResponse response = httpclient.execute(httppost);%0A%0A            HttpEntity entity = response.getEntity(
+URL url = new URL(params%5B0%5D);%0A            HttpURLConnection conn = (HttpURLConnection) url.openConnection();%0A            conn.setRequestMethod(%22POST%22);%0A%0A            InputStream is = new BufferedInputStream(conn.getInputStream()
 );%0A%0A
@@ -1913,22 +1913,18 @@
     if (
-entity
+is
  != null
@@ -1931,115 +1931,8 @@
 ) %7B%0A
-                // A Simple JSON Response Read%0A                InputStream instream = entity.getContent();%0A
     
@@ -1979,15 +1979,9 @@
 ng(i
-nstream
+s
 );%0A 
@@ -2008,16 +2008,17 @@
  %7D catch
+ 
 (Excepti
@@ -2132,17 +2132,16 @@
  return 
- 
 result;%0A
@@ -3746,9 +3746,8 @@
 %0A    %7D%0A%7D
-%0A

Use HttpURLConnection instead of HttpPost to be compliant with target sdk > 21