import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.LayeredSocketFactory;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
/**
* HttpTask
*/
public abstract class HttpTask extends AsyncTask<Void,Void,HttpResult> implements OnCancelListener{
private String url="";
private RequestType type;
private List<NameValuePair> paramList;
private boolean cancel = false;
private Throwable error;
public enum RequestType{ HEAD , GET , POST; }
public HttpTask(RequestType type,String url){
this.type = type;
this.url = url;
paramList = new ArrayList<NameValuePair>();
}
public HttpTask(RequestType type,String url,Map<String,String> paramMap){
this.type = type;
this.url = url;
paramList = new ArrayList<NameValuePair>();
for(String key : paramMap.keySet()){
paramList.add(new BasicNameValuePair(key,paramMap.get(key)));
}
}
/** 結果処理 */
protected abstract void onResult(RequestType type,boolean isNormalResponse,HttpResult result);
/** 通信開始前処理 */
protected void onStartCommunication(RequestType type,String url){
}
/** 通信終了後処理 */
protected void onEndCommunication(RequestType type,String url){
}
/** cancel時、onEndCommunication の後で呼ばれる。*/
protected void cancelResponse(RequestType type,String url){
}
/** 例外発生時に呼ばれる */
protected void onFailed(Throwable e){
}
@Override
protected final void onPreExecute(){
onStartCommunication(type,url);
}
@Override
protected final HttpResult doInBackground(Void...params){
Result result = null;
try{
HttpResponse response = null;
HttpClient client = null;
if (!url.startsWith("https://") && !url.startsWith("http://")){
throw new IllegalArgumentException("url is error");
}
if (url.startsWith("https://")){
client = new MyHttpClient();
}else if(url.startsWith("http://")){
client = AndroidHttpClient.newInstance("Android");
}else{
throw new RuntimeException("url is error");
}
if (type.equals(RequestType.GET)){
url = paramList.size() < 1 ? url : url + "?" + URLEncodedUtils.format(paramList,"utf-8");
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("User-Agent","Android");
response = client.execute(httpGet);
}else if(type.equals(RequestType.POST)){
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("User-Agent","Android");
httpPost.setEntity(new UrlEncodedFormEntity(paramList,"utf-8"));
response = client.execute(httpPost);
}else{
HttpHead httpHead = new HttpHead(url);
httpHead.addHeader("User-Agent","Android");
response = client.execute(httpHead);
}
result = new Result(response.getStatusLine().getStatusCode(),response.getAllHeaders());
if (result.getStatusCode()==HttpStatus.SC_OK){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
response.getEntity().writeTo(stream);
result.setBytes(stream.toByteArray());
stream.close();
}
}catch(Exception e){
error = e;
}
return result;
}
@Override
protected final void onPostExecute(HttpResult result){
onEndCommunication(type,url);
if (!cancel && result != null && error==null){
onResult(type,result.getStatusCode()==HttpStatus.SC_OK,result);
}else{
if (error != null){
onFailed(error);
}
}
}
@Override
public final void onCancel(DialogInterface dialog){
cancel = true;
this.cancel(true);
}
@Override
protected final void onCancelled(){
onEndCommunication(type,url);
cancelResponse(type,url);
if (error != null){
onFailed(error);
}
}
//
class MyHttpClient extends DefaultHttpClient{
@Override
protected ClientConnectionManager createClientConnectionManager(){
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
try{
SSLContext sslcontext = SSLContext.getInstance(SSLSocketFactory.TLS);
sslcontext.init(null,new TrustManager{ new X509TrustManager(){
@Override
public void checkClientTrusted(X509Certificate chain,String authType) throws CertificateException{
}
@Override
public void checkServerTrusted(X509Certificate chain,String authType) throws CertificateException{
}
@Override
public X509Certificate getAcceptedIssuers(){
return new X509Certificate[0];
}
}},new SecureRandom());
final javax.net.ssl.SSLSocketFactory socketfactory = sslcontext.getSocketFactory();
registry.register(new Scheme("https",new LayeredSocketFactory(){
@Override
public Socket createSocket(Socket socket,String host,int port,boolean autoClose)
throws IOException,UnknownHostException{
return socketfactory.createSocket(socket,host,port,autoClose);
}
@Override
public Socket connectSocket(Socket sock,String host,int port
,InetAddress localAddress,int localPort,HttpParams params)
throws IOException,UnknownHostException,ConnectTimeoutException{
SSLSocket sslsock = (SSLSocket)*1;
if (localAddress != null || localPort > 0){
InetSocketAddress isa = new InetSocketAddress(localAddress,localPort);
sslsock.bind(isa);
}
int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
int soTimeout = HttpConnectionParams.getSoTimeout(params);
InetSocketAddress remoteAddress;
remoteAddress = new InetSocketAddress(host,port);
sslsock.connect(remoteAddress, connTimeout);
sslsock.setSoTimeout(soTimeout);
return sslsock;
}
@Override
public Socket createSocket() throws IOException{
return socketfactory.createSocket();
}
@Override
public boolean isSecure(Socket sock) throws IllegalArgumentException{
return true;
}
},443));
}catch(Exception e){
throw new RuntimeException(e);
}
return new SingleClientConnManager(getParams(),registry);
}
}
class Result implements HttpResult{
private int code;
private byte bytes;
private Header headers;
protected Result(int code,Header headers){
this.code = code;
this.headers = headers;
}
@Override
public int getStatusCode(){
return this.code;
}
@Override
public byte getBytes(){
return this.bytes;
}
@Override
public String getString(){
return new String(this.bytes);
}
@Override
public Header getHeaders(){
return this.headers;
}
protected void setBytes(byte bytes){
this.bytes = bytes;
}
}
}
-------------------------------------------------------------------
import org.apache.http.Header;
/**
* HttpResult HTTP通信結果
*/
public interface HttpResult{
/**
* @return HTTP status code
*/
public int getStatusCode();
/**
* @return org.apache.http.Header
*/
public Header getHeaders();
/**
* @return 取得コンテンツ
*/
public byte getBytes();
/**
* @return 取得コンテンツ
*/
public String getString();
}
*1:sock != null) ? sock : createSocket(