TCP传输中使用AES加密和gizp压缩(2)--封装TcpUtil,封装后实现登陆
2015-05-31 05:30
627 查看
一、TcpUtil
TcpRequsetCallBack
BaseRespBean
二、登陆中客户端重要涉及的类
1.LoginReqBean
2.BaseRespBean
3.LoginRespBean
三、登陆中客户端登陆方法
四、java控制台程序模拟的后台主要方法
五、主要效果
源码下载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | /** *@authorqiwenming *@time2015年5月31日上午4:24:02 *@说明TcpUtil */ public class TcpUtil{ private OutputStreamoutputStream; private InputStreaminputStream; private Socketsocket; private ProgressDialogpd; //进度提示框 private StringTAG=TcpUtil. class .getName(); /** *实体类转为json * *@parambeanClass *@return */ public <T>StringgetSendData(TbeanClass){ if (beanClass== null ){ return "" ; } Tbean=beanClass; Gsongson= new Gson(); Stringstr=gson.toJson(bean); return str; } /** *拼接请求字符串 * *@parambeanClass *@paramserverName *@return */ public <T>StringgetRequestString(TbeanClass,StringserverName){ StringBuildersb= new StringBuilder(); sb.append( "{" ); //header拼装 sb.append( "\"header\":{" ); sb.append( "\"service_name\":\"" +serverName+ "\"" ); sb.append( "}," ); //body拼装 sb.append( "\"body\":" ); sb.append(getSendData(beanClass)); sb.append( "}" ); return sb.toString(); } /** *@paramcontext *@paramMessage *提示框信息 *@paramisShowDialog *是否显示提示框 *@paramcallBack *回调 *@parambeanClass *@paramserviceName *调用的服务器名 */ public <T> void requestData( final Contextcontext, final Stringmessage, boolean isShowDialog, final TcpRequsetCallBackcallBack, TbeanClass,StringserviceName){ //创建一个AsyncTask去这行请求为什么 new MyTast<T>(context,message,isShowDialog,callBack,beanClass,serviceName).execute( "" ); } /** *发送请求数据 * *@paramrequestStr *请求数据 *@throwsException *异常 */ public void send(StringrequestStr) throws Exception{ if (outputStream== null ){ outputStream=socket.getOutputStream(); } //编码 byte []encryptBytes=AESUtil.encrypt(requestStr.getBytes()); //压缩 byte []compressBytes=GZipUtils.compress(encryptBytes); //写入数据流操作 DataOutputStreamdos= new DataOutputStream(outputStream); dos.writeInt(compressBytes.length); dos.write(compressBytes); } /** *接收数据 * *@return服务器返回的字符数据 *@throwsException */ public Stringreceive() throws Exception{ if (inputStream== null ){ inputStream=socket.getInputStream(); } //获取输入流读取服务端传递过来的流 DataInputStreamdin= new DataInputStream(inputStream); int availableLen=din.readInt(); //阻塞方法 byte []data=receiveBytes(din,availableLen); //读取字节数据 byte []uncompress=GZipUtils.decompress(data); byte []decrypt=AESUtil.decrypt(uncompress); return new String(decrypt, "UTF-8" ); } /** *得到接收的byte数组数据 * *@paramis *输入流(服务端传递过来的数据) *@paramlength *读取的长度 *@return字节数组 *@throwsIOException */ private byte []receiveBytes(InputStreamis, int length) throws IOException{ int tmpLength= 1024 ; //每次读取最大缓冲区大小 byte []ret= new byte [length]; int readed= 0 ,offset= 0 ,left=length; byte []bs= new byte [tmpLength]; while (left> 0 ){ try { //读取数据到bs数据中,读取的长度返回到readed中 readed=is.read(bs, 0 ,Math.min(tmpLength,left)); if (readed==- 1 ) //读取结束 break ; System.arraycopy(bs, 0 ,ret,offset,readed); //copy数据 } finally { offset+=readed; //更新读取的位置 left-=readed; //读取的长度减小 } } return ret; } /** *关闭流 * *@throwsIOException */ public void disconnect() throws IOException{ if (outputStream!= null ){ outputStream.close(); } if (inputStream!= null ){ inputStream.close(); } if (socket!= null &&!socket.isClosed()){ socket.shutdownInput(); socket.shutdownOutput(); socket.close(); } } /** *@authorqiwenming *@param<T> *@creation2015-5-19下午3:39:56 *@instruction网络请求(参数,进度,结果) */ class MyTast<T> extends AsyncTask<String,Integer,NetResponse>{ private Contextcontext; private Stringmessage; private boolean isShowDialog; private TcpRequsetCallBackcallBack; private TbeanClass; private StringserviceName; public MyTast( final Contextcontext, final Stringmessage, boolean isShowDialog,TcpRequsetCallBackcallBack,TbeanClass, StringserviceName){ this .context=context; this .message=message; this .isShowDialog=isShowDialog; this .callBack=callBack; this .beanClass=beanClass; this .serviceName=serviceName; } /** *请求数据前 */ protected void onPreExecute(){ if (!ConnectUtils.isNetworkConnected(context)){ Toast.makeText(context, "网络未连接,请检查网络" , 0 ).show(); return ; } if (isShowDialog){ //判断是否需要显示dialog pd= new ProgressDialog(context); if ( this .message== null ){ //判断要显示的文字 pd.setMessage( "正在加载数据" ); } else { pd.setMessage(message); } pd.show(); } } /** *请求数据中 */ protected NetResponsedoInBackground(String...params){ NetResponsenrp= new NetResponse(); try { socket= new Socket( "192.168.1.106" , 8888 ); socket.setSoTimeout( 10 * 1000 ); //这里不使用params使用他会加[]所以不用 StringrequestMsg=getRequestString(beanClass,serviceName); if (MyApplication.isShowLog){ //如果需要打印日志的话打印数据 Log.i(serviceName, "请求数据###" +requestMsg); } send(requestMsg); StringrespMsg=receive(); //接收数据 nrp.status=ResponseStatus.OK; nrp.responseMsg=respMsg; if (MyApplication.isShowLog){ //如果需要打印日志的话打印数据 Log.i(serviceName, "响应数据" +respMsg); } } catch (IOExceptione){ nrp.status=ResponseStatus.ERR; nrp.responseMsg=TAG+ "---doInBackground():IOException:请求或者接收数据时候出问题" ; nrp.exception=e; //e.printStackTrace(); } catch (Exceptione){ nrp.status=ResponseStatus.ERR; nrp.responseMsg=TAG+ "---doInBackground():IOException:请求或者接收数据时候出问题" ; nrp.exception=e; //e.printStackTrace(); } finally { //关闭对话框 if (pd!= null &&pd.isShowing()){ pd.dismiss(); } try { if (socket!= null &&!socket.isClosed()){ socket.shutdownInput(); socket.shutdownOutput(); socket.close(); socket= null ; } if (outputStream!= null ){ outputStream.close(); } if (inputStream!= null ){ inputStream.close(); } } catch (IOExceptione){ //关闭流除了问题 //e.printStackTrace(); nrp.status=ResponseStatus.ERR; nrp.responseMsg=TAG+ "---doInBackground():IOException:关闭流除了问题" ; nrp.exception=e; // callBack.onErr(nrp); } } return nrp; } /** *请求数据结束后 */ protected void onPostExecute(NetResponseresult){ if (ResponseStatus.OK==result.status){ //请求成功 callBack.onRequestSuccess(result.responseMsg); } else { //请求失败 callBack.onErr(result); } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | /** *@authorqiwenming *@time2015年5月30日下午11:35:41 *@说明Tcp请求的回调类 */ public abstract class TcpRequsetCallBack<TR>{ // private Class<TR>beanClass; private StringTAG=TcpRequsetCallBack. class .getName(); /** *构造函数 *@param<TR> *@parambeanClass */ public TcpRequsetCallBack(Class<TR>beanClass){ this .beanClass=beanClass; } /** *请求成功的方法 *@paramresponseMsg */ public <T> void onRequestSuccess(StringresponseMsg){ Gsongson= new Gson(); try { TRbean=gson.fromJson(responseMsg,beanClass); if (bean instanceof BaseRespBean){ BaseRespBeanbnBean=(BaseRespBean)bean; if (! "0000" .equals(bnBean.result_code)){ //这里的判断根据规定的响应码来判断 onfail(bnBean.result_code,bnBean.result_msg); return ; } onSuccess(bean); } } catch (JsonSyntaxExceptione){ NetResponsenetRspJson= new NetResponse(); netRspJson.exception=e; netRspJson.responseMsg=TAG+ ":onRequestSuccess():JsonSyntaxException:响应数据转换json的时候处理问题" ; onErr(netRspJson); } }; /** *得到正确的数据 *@paramheader *@paramresultMsg *@paramresultCode */ public abstract void onSuccess(TRbean); /** *数据错误 *@paramfailDesc错误信息 *@paramresult_code错误码 */ public void onfail(Stringresult_code,StringfailDesc){ Log.e(TAG+ ".onfail" , "请求数据失败:result_code:" +result_code+ "failDesc:" +failDesc); }; /** *请求报错 *@paramnetQuest */ public void onErr(NetResponsenetRsp){ Log.e(TAG+ ".onErr" ,netRsp.responseMsg); netRsp.exception.printStackTrace(); }; } |
1 2 3 4 5 6 7 8 9 | /** *@authorqiwenming *@time2015年5月31日上午12:11:18 *@说明响应基类 */ public class BaseRespBean implements Serializable{ public Stringresult_code; public Stringresult_msg; } |
1.LoginReqBean
1 2 3 4 5 6 7 8 9 | /** *@authorqiwenming *@time2015年5月30日下午11:57:40 *@说明登陸請求的javabean */ public class LoginReqBean implements Serializable{ public Stringusername; public Stringpassword; } |
1 2 3 4 5 6 7 8 9 | /** *@authorqiwenming *@time2015年5月31日上午12:11:18 *@说明响应基类 */ public class BaseRespBean implements Serializable{ public Stringresult_code; public Stringresult_msg; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | /** *@authorqiwenming *@time2015年5月31日上午12:10:41 *@说明登陆响应类 */ public class LoginRespBean extends BaseRespBean{ public LoginDatadata; public class LoginData implements Serializable{ public StringnickName; public int age; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | /** *登陆 * *@paramv */ public void toLogin(Viewv){ Stringname=nameEdt.getText().toString().trim(); Stringpwd=pwdEdt.getText().toString().trim(); if ( "" .equals(name)){ Toast.makeText( this , "用户名为空" , 0 ).show(); return ; } if ( "" .equals(name)){ Toast.makeText( this , "密码为空" , 0 ).show(); return ; } LoginReqBeanbean= new LoginReqBean(); bean.username=name; bean.password=pwd; new TcpUtil().requestData( this , "登陆请求中..." , true , new TcpRequsetCallBack<LoginRespBean>(LoginRespBean. class ){ @Override public void onSuccess(LoginRespBeanbean){ //登陆成功 Intenti= new Intent(MainActivity. this ,HomeActivity. class ); i.putExtra( "loginbean" ,bean); startActivity(i); MainActivity. this .finish(); } @Override public void onfail(Stringresult_code,StringfailDesc){ //登陆失败 super .onfail(result_code,failDesc); Toast.makeText(MainActivity. this ,result_code+ ":" +failDesc, 0 ).show(); } },bean, "loginServer" ); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | /** *@authorxiaoming *@time2015年5月30日下午5:01:01 *@说明AesDemo */ public class AesDemo{ public static void main(String[]args){ test(); } public static void test(){ ServerSocketss= null ; try { ss= new ServerSocket( 8888 ); while ( true ){ final Sockets=ss.accept(); new Thread( new Runnable(){ public void run(){ try { DataInputStreamdis= new DataInputStream( s.getInputStream()); //读取数据 byte []recData=( new TcpUtil()).readData(dis); System.out.println( "长度:" +recData.length); ////解压缩 byte []uncompress=GZipUtils.decompress(recData); //解密 byte []decrypt=AESUtil.decrypt(uncompress); //======================响应部分================================ DataOutputStreamdos= new DataOutputStream( s.getOutputStream()); byte []respData=handlerData(decrypt); //加密 byte []encrypt=AESUtil.encrypt(respData); ////压缩 byte []compress=GZipUtils.compress(encrypt); dos.writeInt(compress.length); //把数据的长度写过去 dos.write(compress); dos.flush(); s.shutdownOutput(); } catch (InvalidCipherTextExceptione){ e.printStackTrace(); } catch (IOExceptione){ e.printStackTrace(); } catch (Exceptione){ e.printStackTrace(); } } }).start(); } } catch (Exceptione){ e.printStackTrace(); } finally { try { //关闭资源 if (ss!= null ){ ss.close(); } } catch (IOExceptione){ e.printStackTrace(); } } } /** *实体类转为json * *@parambeanClass *@return */ public static <T>StringgetSendData(TbeanClass){ if (beanClass== null ){ return "" ; } Tbean=beanClass; Gsongson= new Gson(); Stringstr=gson.toJson(bean); return str; } /** *处理数据 */ public static byte []handlerData( byte []decrypt){ StringreqMsg= new String(decrypt); System.out.println( "请求的数据:" +reqMsg); Gsongson= new Gson(); //获得数据 LoginReqBeanbean=gson.fromJson(reqMsg,LoginReqBean. class ); LoginRespBeanrespBean= new LoginRespBean(); if ( null !=bean){ if ( "loginServer" .equals(bean.header.service_name)){ if ( "xiaoming" .equals(bean.body.username)){ if ( "520" .equals(bean.body.password)){ respBean.result_code= "0000" ; respBean.result_msg= "登陆成功" ; respBean.data.nickName= "小明" ; respBean.data.age= 24 ; } else { respBean.data= null ; respBean.result_code= "1001" ; respBean.result_msg= "密码错误" ; } } else { respBean.data= null ; respBean.result_code= "1002" ; respBean.result_msg= "用户名错误" ; } } else { respBean.data= null ; respBean.result_code= "1003" ; respBean.result_msg= "没有这个服务名" ; } } else { respBean.data= null ; respBean.result_code= "1004" ; respBean.result_msg= "数据为空" ; } StringrespMsg=getSendData(respBean); System.out.println( "响应的数据:" +respMsg); return respMsg.getBytes(); } } |
相关文章推荐
- 虚拟机中 CentOS 网络配置图解
- 嵌入式软件开发培训笔记——Linux网络编程及I/O模型
- HTTP-API-DESIGN 怎样设计一个合理的 HTTP API (一)
- Java基础——网络编程
- android 访问网络四 (基于android-async-http-master)
- android 访问网络三 (基于httpclient)
- 学习笔记一:TCP与UDP通信协议
- android 访问网络二 (基于httpurlconnection post)
- http://blog.sina.com.cn/s/blog_a3d2fd2d0101hyu7.html
- 使用CNN(convolutional neural nets)检测脸部关键点教程(三):卷积神经网络训练和数据扩充
- android 中访问网络介绍 一 (基于httpurlconnection 的中get请求)
- TCP传输中使用AES加密和gizp压缩
- TCP传输中使用AES加密和gizp压缩
- 实时监控Android设备网络封包
- can not find the tag library descriptor for http //java.sun.com/jsp
- 跨平台网络数据传输过程中的主机字节顺序和网络字节顺序
- linux基础网络设置
- HTTP语言
- 网络工程师必备素质-IP地址练习题
- 网络编程中close与shutdown区别