非同期タスクでSandBoxにアクセスする 3

通信を実行するクラス
SandBox .java

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

import android.net.Uri;
import android.net.Uri.Builder;
import android.util.Log;

/**
 * サンドボックス 通信処理クラス
 * @author Ryan's Factory
 * @since 2014/10/01
 */
public class SandBox {
	
	/**
	 * ログのタグ
	 */
	private final String LOG_TAG = this.getClass().getSimpleName();
	/**
	 * クエリーパラメータのクラス
	 */
	public class Requestor {
		/**
		 * パラメータの名前
		 */
		private String name;
		/**
		 * パラメータの値
		 */
		private String parmeter;
		
		public Requestor(String name,String parmeter) {
			this.name = name;
			this.parmeter = parmeter;
		}

		public String getName() {
			return name;
		}

		public String getParmeter() {
			return parmeter;
		}
	}
	/**
	 * 接続のタイムアウト
	 * 初期値:3分
	 */
	private static final int CONNECTION_TIMEOUT = 1000 * 60 * 3;
	private int connectiion_timeout = CONNECTION_TIMEOUT;
	/**
	 * ソケットのタイムアウト
	 * 初期値:3分
	 */
	private static final int SOKET_TIMEOUT =  1000 * 60 * 3;
	private int soket_timeout = SOKET_TIMEOUT;
	/**
	 * キャラセット
	 */
	private static final String CHARSET = "utf-8";
	/**
	 * エラーコード
	 */
	private int error = 0;
	/**
	 * IOException が発生した
	 */
	public static final int IO_ERROR = 1000;
	/**
	 * ClientProtocolException が発生した
	 */
	public static final int CLIENTPROTOCOL_ERROR = 1001;
	/**
	 * プロトコル
	 */
	private String scheme;
	/**
	 * ドメイン
	 */
	private String authority;
	/**
	 * パス
	 */
	private String path;
	/**
	 * クエリーパラメータ
	 */
	private Map<String, String> mapRequestor = null;
	/**
	 * プログレスオブジェクト
	 */
	private Object progress = null;
	/**
	 * コンストラクタ
	 */
	public SandBox() {
		mapRequestor = new HashMap<String,String>();
	}
	
	public void setScheme(String scheme) {
		this.scheme = scheme;
	}

	public void setAuthority(String authority) {
		this.authority = authority;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public void setConnectiion_timeout(int connectiion_timeout) {
		this.connectiion_timeout = connectiion_timeout;
	}

	public void setSoket_timeout(int soket_timeout) {
		this.soket_timeout = soket_timeout;
	}
	
	public void putRequestor(String key,String value) {
		mapRequestor.put(key, value);
	}
	
	public Requestor[] getRequestor() {
		Requestor[] params;
		if ( mapRequestor.isEmpty() ) {
			params = new Requestor[1];
			params[0]= new Requestor("","");
		} else {
			params = new Requestor[mapRequestor.size()];
			int i = 0;
			for (Iterator<Map.Entry<String, String>> it = mapRequestor.entrySet().iterator(); it.hasNext();i++ ) {
			    Map.Entry<String, String> entry = it.next();
			    params[i] = new Requestor(entry.getKey(),entry.getValue());
			}
		}
		return params;
	}
	
	/**
	 * プログレスオブジェクトを設定
	 * @param progress
	 */
	public void setProgress(Object progress) {
		this.progress = progress;
	}

	/**
	 * プログレスオブジェクトを取得
	 * @return
	 */
	public Object getProgress() {
		return progress;
	}

	public String request(Requestor[] params) {
		String resulte = "";
		error = 0;
		// クライアント生成
		HttpClient httpClient = createHttpClient();
		// リクエスト生成
		HttpUriRequest httpRequest = createHttpUriRequest(params);
		// レスポンス取得
		HttpResponse httpResponse = getHttpResponse(httpClient,httpRequest);
		// レスポンス正常?
		if ( isResponseOK(httpResponse) ) {
			// データ取得
			try {
				resulte = getTextResponse(httpResponse);
			} catch (IOException e) {
				error = IO_ERROR;
				Log.e(LOG_TAG, "" + e.getMessage() );
			}
		}
		// 切断
		httpClient.getConnectionManager().shutdown();
		return resulte;
	}
	
	public boolean isSuccess() {
		if ( 0 == error) {
			return true;
		}
		return false;
	}

	public int getErrorCode() {
		return error;
	}
	
	private boolean isResponseOK(HttpResponse httpResponse) {
		if (httpResponse != null ) {
			if ( httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK ) {
				return true;
			}
			error = httpResponse.getStatusLine().getStatusCode();
			Log.e(LOG_TAG, "" + httpResponse.getStatusLine().getReasonPhrase() );
		}
		return false;
	}
	
	private String getTextResponse(HttpResponse httpResponse) throws IOException {
		String resulte = "";
		HttpEntity httpEntity = httpResponse.getEntity();
		if( null == httpEntity ) {
			error = IO_ERROR;
			return "";
		}
		try {
			resulte = EntityUtils.toString(httpEntity, CHARSET);
		} catch (Exception e) {
			error = IO_ERROR;
			Log.e(LOG_TAG, "" + e.getMessage() );
		} finally {
			httpEntity.consumeContent();
		}
		return resulte;
	}

	private HttpClient createHttpClient() {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), connectiion_timeout);
		HttpConnectionParams.setSoTimeout(httpClient.getParams(), soket_timeout);
		return httpClient;
	}

	private HttpUriRequest createHttpUriRequest(Requestor[] params) {
		return new HttpGet(createUriBuilder(params).toString());
	}
	
	private Builder createUriBuilder(Requestor[] params) {
		Uri.Builder uriBuilder = new Uri.Builder();
		uriBuilder.scheme(scheme);
		uriBuilder.authority(authority);
		uriBuilder.path(path);
		for(Requestor req: params) {
			uriBuilder.appendQueryParameter(req.getName(),req.getParmeter());
		}
		return uriBuilder;
	}
	
	private HttpResponse getHttpResponse(HttpClient httpClient, HttpUriRequest httpRequest)  {
		HttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpRequest);
		} catch (ClientProtocolException e) {
			error = CLIENTPROTOCOL_ERROR;
			Log.e(LOG_TAG, "" + e.getMessage() );
		} catch (IOException e) {
			error = IO_ERROR;
			Log.e(LOG_TAG, "" + e.getMessage() );
		}
		return httpResponse;
	}
	
}

通信処理を行なう関数 String request(Requestor[] params)
パラメータを格納するクラス Requestor は使い回しするクラスではないから内部クラスとする。

通信処理が成功したか検査する関数  isSuccess()

細かいところは実際に使用する例で説明する

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>