본문 바로가기

Android

android http, https 통신

//request


SchemeRegistry schemeRegistry = new SchemeRegistry();// 스키마 등록

schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));// http

schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));// ssl


HttpParams httpParams = new BasicHttpParams();// thread safe

httpParams.setParameter(HttpConnectionParams.SO_TIMEOUT, TISPreference.NET_SO_TIMEOUT);

httpParams.setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, TISPreference.NET_CONN_TIMEOUT);


mCCM = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

mHttpClient = new DefaultHttpClient(mCCM, httpParams);


ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

nameValuePairs.add(new BasicNameValuePair("data", data));//value에 있는 data에는 request보낼 데이터를 삽입한다.(나같은 경우는 gson를 넣어서 보내고했다.)


UrlEncodedFormEntity entityRequest = null;


try {

entityRequest = new UrlEncodedFormEntity(nameValuePairs, TISPreference.NET_ENCODING);


HttpPost httpPost = new HttpPost(url);

httpPost.setEntity(entityRequest);


if (TISPreference.DEBUG)

DLog.v(DLog.Type.NET, "[REQ][" + actionType.getName() + "]" + data);

RequestHandler requestHandler = new RequestHandler(httpPost, actionType, reqModel);

requestHandler.start();


} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}


//response

class RequestHandler extends Thread {


private HttpContext mHttpContext = null;

private HttpPost mHttpPost = null;

private ActionType mActionType = null;

private SuperReqModel mReqModel = null;


RequestHandler(HttpPost httpPost, ActionType actionType, SuperReqModel reqModel) {

this.mHttpContext = new BasicHttpContext();

this.mHttpPost = httpPost;

this.mActionType = actionType;

this.mReqModel = reqModel;

}


@Override

public void run() {

// TODO Auto-generated method stub

super.run();


boolean isNotError = false;

try {


HttpResponse response = mHttpClient.execute(mHttpPost, mHttpContext);


HttpEntity entity = response.getEntity();


if (entity != null) {

String result = EntityUtils.toString(entity);//response를 String로 뽑았음 이걸 사용해도됨.

}

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}


이전 맨처음에 포스팅한 것보다 성능은 더 낫다고 생각함.