Android + https 实现 文件上传
程序员文章站
2022-10-16 12:30:16
package com.example.wbdream.zigvine; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ContentValues; import... ......
package com.example.wbdream.zigvine; import android.annotation.suppresslint; import android.app.activity; import android.content.contentvalues; import android.content.intent; import android.database.cursor; import android.database.sqlite.sqlitedatabase; import android.os.bundle; import android.os.environment; import android.os.handler; import android.os.message; import android.support.annotation.nonnull; import android.support.annotation.nullable; import android.support.v4.app.fragment; import android.support.v7.widget.divideritemdecoration; import android.support.v7.widget.linearlayoutmanager; import android.support.v7.widget.recyclerview; import android.util.log; import android.view.layoutinflater; import android.view.menu; import android.view.menuinflater; import android.view.menuitem; import android.view.view; import android.view.viewgroup; import android.widget.toast; import com.example.wbdream.zigvine.friends.friendsdata; import com.example.wbdream.zigvine.friends.friendsrecycleradapter; import com.example.wbdream.zigvine.https.uploadfile; import com.leon.lfilepickerlibrary.lfilepicker; import com.leon.lfilepickerlibrary.utils.constant; import org.json.jsonexception; import org.json.jsonobject; import java.io.bufferedreader; import java.io.datainputstream; import java.io.dataoutputstream; import java.io.file; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.filereader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.net.httpurlconnection; import java.net.malformedurlexception; import java.net.url; import java.security.keymanagementexception; import java.security.nosuchalgorithmexception; 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.uuid; import javax.net.ssl.hostnameverifier; import javax.net.ssl.httpsurlconnection; import javax.net.ssl.sslcontext; import javax.net.ssl.sslsession; import javax.net.ssl.trustmanager; import javax.net.ssl.x509trustmanager; public class friendslist extends fragment { private list<jsonobject> mdata = null; private friendsdata sc = null; private sqlitedatabase db = null; private friendsrecycleradapter friendsrecycleradapter = null; private static final int file_code = 0; private static final string tag = "friendslist"; private string uploadpath = null; @nullable @override public view oncreateview(@nonnull layoutinflater inflater, @nullable viewgroup container, @nullable bundle savedinstancestate) { log.e(tag, "oncreateview: -----finish????-------" ); sethasoptionsmenu(true); final view view = inflater.inflate(r.layout.friends_list,container,false); return view; } @override public void onactivitycreated(@nullable bundle savedinstancestate) { super.onactivitycreated(savedinstancestate); flushdata(); log.e(tag, "onactivitycreated: +++++===================" ); // initdata(); // recyclerview friends_recycler = getactivity().findviewbyid(r.id.friends_recycler); // linearlayoutmanager layoutmanager = new linearlayoutmanager(getcontext()); // friends_recycler.setlayoutmanager(layoutmanager); // friendsrecycleradapter = new friendsrecycleradapter(getcontext(),mdata); // log.e(tag, "onactivitycreated: ====================="+friendsrecycleradapter.hashcode() ); // friendsrecycleradapter.setonitemclicklistener(new friendsrecycleradapter.onitemclicklistener() { // @override // public void onclick(int position) { // toast.maketext(getcontext(),"点击事件"+position,toast.length_short).show(); // // //初始化某人聊天数据 // int uid; // try { // uid = mdata.get(position).getint("uid"); //// cursor cursor = db.rawquery("select * from chatrecord where friends_id = "+ uid,null); // intent intent = new intent(getcontext(),chatactivity.class); // intent.putextra("uid",uid); // startactivity(intent); // // } catch (jsonexception e) { // e.printstacktrace(); // } // // } // }); // friends_recycler.additemdecoration(new divideritemdecoration(getcontext(),divideritemdecoration.vertical)); // friends_recycler.setadapter(friendsrecycleradapter); // // //删除数据库 //// getcontext().deletedatabase("friend1.db"); // // //删除表内容 //// db.execsql("delete from friends"); // //插入数据 // contentvalues values = new contentvalues(); // //// for ( int i=1;i<3;i++) { //// log.e(tag, "onactivitycreated: ______" + "张三" + i); //// values.put("friends_name","李四"+i); //// db.insert("friends", null,values ); //// values.clear(); //// } // // toast.maketext(getcontext(),"初始化数据库",toast.length_short).show(); // cursor cursor = db.rawquery("select friends_name,friendid from friends",null); // if (cursor.movetofirst()){ // do { // string name = cursor.getstring(cursor.getcolumnindex("friends_name")); // log.e(tag, "onactivitycreated: *******"+name +"----"+cursor.getint(cursor.getcolumnindex("friendid"))); // }while(cursor.movetonext()); // // } // cursor.close(); } //添加menu @override public void oncreateoptionsmenu(menu menu, menuinflater inflater) { inflater.inflate(r.menu.friend_list_menu,menu); } //menu点击事件 @override public boolean onoptionsitemselected(menuitem item) { switch (item.getitemid()){ case r.id.add_friend: //跳转页面 toast.maketext(getcontext(),"add friend",toast.length_short).show(); intent intent = new intent(getcontext(),addfriendactivity.class); startactivity(intent); break; } return true; } public void initdata() { //创建数据库 sc = new friendsdata(getcontext(),"friend.db",null,4); db = sc.getwritabledatabase(); mdata = new arraylist(); cursor cursor = db.rawquery("select * from friends",null); if (cursor.movetofirst()){ do { jsonobject json=new jsonobject(); try { // log.e(tag, "initdata: _________" +cursor.getstring(cursor.getcolumnindex("friends_name"))); json.put("user_name",cursor.getstring(cursor.getcolumnindex("friends_name"))); json.put("message","你好呀!"); json.put("imageview",""); json.put("uid",cursor.getint(cursor.getcolumnindex("friendid"))); } catch (jsonexception e) { e.printstacktrace(); } mdata.add(json); // log.e(tag, "initdata: ++++"+mdata.size() ); }while(cursor.movetonext()); } cursor.close(); } @override public void onresume() { log.e(tag, "onresume: --------resume------"+friendsrecycleradapter.hashcode() ); log.e(tag, "onresume: ==========="+mdata.size() ); flushdata(); super.onresume(); } //刷新数据 public void flushdata(){ initdata(); recyclerview friends_recycler = getactivity().findviewbyid(r.id.friends_recycler); linearlayoutmanager layoutmanager = new linearlayoutmanager(getcontext()); friends_recycler.setlayoutmanager(layoutmanager); friendsrecycleradapter = new friendsrecycleradapter(getcontext(),mdata); log.e(tag, "onactivitycreated: ====================="+friendsrecycleradapter.hashcode() ); friendsrecycleradapter.setonitemclicklistener(new friendsrecycleradapter.onitemclicklistener() { int uid; @override public void onclick(int position) { toast.maketext(getcontext(),"点击事件"+position,toast.length_short).show(); log.e(tag, "onclick: ----点击事件----" ); //初始化某人聊天数据 try { uid = mdata.get(position).getint("uid"); // cursor cursor = db.rawquery("select * from chatrecord where friends_id = "+ uid,null); intent intent = new intent(getcontext(),chatactivity.class); intent.putextra("uid",uid); // startactivity(intent); log.e(tag, "onclick: ----https--" ); @suppresslint("handlerleak") final handler handler = new handler(){ @override public void handlemessage(message msg) { super.handlemessage(msg); switch (msg.what){ case 111: toast.maketext(getcontext(),"jjjj"+msg.obj,toast.length_short).show(); break; } } }; //文件传输 string sdpath; // sdpath = "/mnt/"; // sdpath = getcontext().getfilesdir(); log.e(tag, "onclick: ----————"+getcontext().getfilesdir() ); log.e(tag, "onclick: ----————"+environment.getexternalstoragedirectory() ); file file = new file(getcontext().getfilesdir(),"a2.txt"); log.e(tag, "onclick: cahgnjan ==========="+!file.exists()+" "+getcontext().getfilesdir() +getcontext().getexternalcachedir() ); try { file fp=getcontext().getfilesdir(); if (!fp.exists()){ fp.mkdirs(); log.e(tag, "onclick: --------创建文件夹" ); } getcontext().getfilesdir().mkdirs(); if (!file.exists()){ log.e(tag, "onclick: ———创建不成吗—————" ); file.createnewfile(); system.out.print("jsdhj"); log.e(tag, "onclick: --------创建了吗" ); } fileinputstream inputstream = new fileinputstream(file); inputstream.close(); fileoutputstream outputstream = new fileoutputstream(file); outputstream.write("hello".getbytes()); outputstream.close(); } catch (ioexception e) { e.printstacktrace(); } new lfilepicker().withsupportfragment(friendslist.this) .withrequestcode(constant.icon_style_blue) .withtitle("文件管理器") // .withstartpath("/storage/emulated/0/download")//指定初始显示路径 .withstartpath(getcontext().getfilesdir().tostring())//指定初始显示路径 .withnotfoundbooks("至少选择一个文件") .start(); //###############注意这里是 get 请求 ########## ///////////////// // new thread(new runnable() { // // @override // public void run() { // gethttps(); // } // public void gethttps(){ // log.e(tag, "gethttps:-------执行了吗------ https://192.168.1.34:8000/index/" ); // string https = "https://192.168.1.34:8000/index/"; // try { // sslcontext sc = sslcontext.getinstance("tls"); // sc.init(null,new trustmanager[]{new mytrustmanager()},new securerandom()); // httpsurlconnection.setdefaultsslsocketfactory((sc.getsocketfactory())); // httpsurlconnection.setdefaulthostnameverifier(new myhostnameverifier()); // httpsurlconnection conn = (httpsurlconnection)new url(https).openconnection(); // conn.setdooutput(true); // conn.setdoinput(true); // log.e(tag, "gethttps: ++++++结果111+++++" ); // // conn.connect(); // log.e(tag, "gethttps: ++++++结果2222+++++" ); // bufferedreader br = new bufferedreader(new inputstreamreader(conn.getinputstream())); // stringbuffer sb = new stringbuffer(); // string line; // while ((line = br.readline())!=null){ // sb.append(line); // } // log.e(tag, "gethttps: ++++++结果+++++"+sb.tostring() ); // message msg = new message(); // msg.what=111; // msg.obj=sb.tostring(); // handler.sendmessage(msg); // } catch (nosuchalgorithmexception e) { // e.printstacktrace(); // } catch (keymanagementexception e) { // e.printstacktrace(); // } catch (malformedurlexception e) { // e.printstacktrace(); // } catch (ioexception e) { // e.printstacktrace(); // } // } // class myhostnameverifier implements hostnameverifier{ // @override // public boolean verify(string hostname, sslsession session) { // // todo auto-generated method stub // return true; // } // // } // // class mytrustmanager implements x509trustmanager{ // @override // public void checkclienttrusted(x509certificate[] chain, string authtype) // throws certificateexception { // // todo auto-generated method stub // } // @override // public void checkservertrusted(x509certificate[] chain, string authtype) // // throws certificateexception { // // todo auto-generated method stub // } // @override // public x509certificate[] getacceptedissuers() { // // todo auto-generated method stub // return null; // } // // } // // }).start(); } catch (jsonexception e) { e.printstacktrace(); } } //清空聊天记录 @override public void clearrecord(int position) { try { uid = mdata.get(position).getint("uid"); } catch (jsonexception e) { e.printstacktrace(); } db.execsql("delete from chatrecord where friends_id = "+ uid+";"); cursor cursor2 =db.rawquery("select * from chatrecord ;",null); log.e(tag, "clearrecord: " +cursor2.movetofirst() + db.equals(null)); if (cursor2.movetofirst()){ do { log.e(tag, "clearrecord: 00-----"+cursor2.getstring(cursor2.getcolumnindex("content")) ); }while (cursor2.movetonext()); } log.e(tag, "clearrecord: 8888888888" +"delete from chatrecord where friends_id ="+ uid); } // @override // public void onlongclick(int position) { // toast.maketext(getcontext(),"长按事件",toast.length_short).show(); // log.e(tag, "onlongclick: ___***长按事件**___" ); //// alertdialog.builder builder = new alertdialog.builder(getcontext()); //// builder.settitle("hahahha"); //// builder.show(); // // //长按功能键 // } }); friends_recycler.additemdecoration(new divideritemdecoration(getcontext(),divideritemdecoration.vertical)); friends_recycler.setadapter(friendsrecycleradapter); //删除数据库 // getcontext().deletedatabase("friend1.db"); //删除表内容 // db.execsql("delete from chatrecord"); //插入数据 contentvalues values = new contentvalues(); // for ( int i=1;i<3;i++) { // log.e(tag, "onactivitycreated: ______" + "张三" + i); // values.put("friends_name","李四"+i); // db.insert("friends", null,values ); // values.clear(); // } toast.maketext(getcontext(),"初始化数据库",toast.length_short).show(); cursor cursor = db.rawquery("select friends_name,friendid from friends",null); if (cursor.movetofirst()){ do { string name = cursor.getstring(cursor.getcolumnindex("friends_name")); log.e(tag, "onactivitycreated: *******"+name +"----"+cursor.getint(cursor.getcolumnindex("friendid"))); }while(cursor.movetonext()); } cursor.close(); } @override public void onactivityresult(int requestcode, int resultcode, intent data) { if (resultcode == activity.result_ok) { // list<string> list = data.getstringarraylistextra("paths"); // string path = data.getstringextra("path"); // string param = data.getstringextra("param"); list<string> list = null; list = data.getstringarraylistextra(constant.result_info); //选中文件 if (list.size()>0){ for (string string: list) { log.e(tag, "onactivityresult: *************"+string ); file file =new file(string); uploadpath = string; //https请求 new thread(new runnable() { @override public void run() {
//################ 这里是 认证所有证书 trustallcerts信任所有的证书###################
handlesslhandshake();
//################ https post 请求 ############# httppost("https://192.168.1.32:8000/index/up","/data/user/0/com.example.wbdream.zigvine/files/a2.txt","a2.txt"); // httppost("https://192.168.1.32:8000/index/up",string,file.getname()); } }).start(); try { filereader fr=new filereader(file); byte[] bytes=new byte[1024]; bufferedreader br = new bufferedreader(fr); string s=""; while ((s=br.readline())!=null){ log.e(tag, "onactivityresult: =============="+s ); } } catch (filenotfoundexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } } } } } /** * 往服务器上上传文本 比如log日志 * @param urlstr 请求的url * @param uploadfile log日志的路径 * /mnt/shell/emulated/0/log/log.log * @param newname log日志的名字 log.log * @return */ public static void httppost(string urlstr,string uploadfile,string newname) { log.e(tag,"urlstr="+urlstr+";uploadfile="+uploadfile+";newname="+newname ); string end = "\r\n"; string twohyphens = "--"; string boundary = "*****";//边界标识 int time_out = 10*1000; //超时时间 httpsurlconnection con = null; dataoutputstream ds = null; inputstream is = null; try { url url = new url(urlstr); con = (httpsurlconnection) url.openconnection(); log.e(tag, "httppost: 1111111111" ); con.setreadtimeout(time_out); con.setconnecttimeout(time_out); /* 允许input、output,不使用cache */ con.setdoinput(true); con.setdooutput(true); con.setusecaches(false); // 设置http连接属性 con.setrequestmethod("post");//请求方式 con.setrequestproperty("connection", "keep-alive");//在一次tcp连接中可以持续发送多份数据而不会断开连接 con.setrequestproperty("charset", "utf-8");//设置编码 con.setrequestproperty("content-type", "multipart/form-data;boundary=" + boundary);//multipart/form-data能上传文件的编码格式 log.e(tag, "httppost: ------------" ); ds = new dataoutputstream(con.getoutputstream()); log.e(tag, "httppost: 2222222222" ); ds.writebytes(twohyphens + boundary + end); ds.writebytes("content-disposition: form-data; " + "name=\"stblog\";filename=\"" + newname + "\"" + end); ds.writebytes(end); // 取得文件的fileinputstream fileinputstream fstream = new fileinputstream(uploadfile); log.e(tag, "httppost: 333333333333" ); /* 设置每次写入1024bytes */ int buffersize = 1024; byte[] buffer = new byte[buffersize]; int length = -1; /* 从文件读取数据至缓冲区 */ while ((length = fstream.read(buffer)) != -1) { /* 将资料写入dataoutputstream中 */ ds.write(buffer, 0, length); } ds.writebytes(end); ds.writebytes(twohyphens + boundary + twohyphens + end);//结束 fstream.close(); ds.flush(); /* 取得response内容 */ is = con.getinputstream(); int ch; stringbuffer b = new stringbuffer(); while ((ch = is.read()) != -1) { b.append((char) ch); } /* 将response显示于dialog */ log.e(tag, "httppost: ------上传成功-----"); } catch (exception e) { e.printstacktrace(); log.e(tag, "httppost: ======----"+e ); log.e(tag, "httppost: --------上传失败----" ); }finally { /* 关闭dataoutputstream */ if(ds!=null){ try { ds.close(); } catch (ioexception e) { e.printstacktrace(); } } if (is != null) { try { is.close(); } catch (ioexception e) { e.printstacktrace(); } } if (con != null) { con.disconnect(); } } } public static void handlesslhandshake() { try { trustmanager[] trustallcerts = new trustmanager[]{new x509trustmanager() { public x509certificate[] getacceptedissuers() { return new x509certificate[0]; } @override public void checkclienttrusted(x509certificate[] certs, string authtype) { } @override public void checkservertrusted(x509certificate[] certs, string authtype) { } }}; sslcontext sc = sslcontext.getinstance("tls"); // trustallcerts信任所有的证书 sc.init(null, trustallcerts, new securerandom()); httpsurlconnection.setdefaultsslsocketfactory(sc.getsocketfactory()); httpsurlconnection.setdefaulthostnameverifier(new hostnameverifier() { @override public boolean verify(string hostname, sslsession session) { return true; } }); } catch (exception ignored) { } } }
下一篇: 向路由组件传递参数2种方法