Android ksoap調用webservice批量上傳多張圖片詳解
這幾天一直在開發app,哎呀,什么都是第一接觸,想想自己自學Java,然后自學Android,一直沒有放棄,曾想放棄的,但是想到爸媽供我上學,不能在宿舍里面玩游戲,加入學校實驗室,一天沒課就來著里學習,當然這里也有志同道合的人,一起努力一起進步!雖然大學這幾年都在努力的學習技術,也沒有參加什么活動的,更別說找個女伴了!還是老老實實的敲代碼,成功給我帶來巨大的潛能,新技術總是吸引著我。自己做項目,哎呀!好像說偏題了,言歸正傳吧!前幾天我們說了Android怎么通過webservice上傳圖片到指定服務器上面,然而這遠遠不能滿足需求,于是我就像怎么上傳多張圖片呀,想來想去,我就上網看了看,哎,都沒有什么具體的代碼,都是你抄我的,我抄你的,也許這就是中國人的習慣,自己不去驗證代碼的正確性就拿過來,真是誤人子弟呀。
于是我一定要寫著一片博文來彌補這個悲傷的空缺,讓Android開發者不在感到苦惱,讓小伙伴們都找到信心。
下面就看我一步一步的寫法吧!大家認真看,可能方法不是完美,金無足赤嘛,但是肯定是我自己一步一步的寫出來的。
首先,小伙伴們一定要去了解Java的線程池管理類,這個類比較重要。ExecutorService 點擊打開
這個老哥講的不錯,了解ExecutorService之后,你看代碼就比較輕松一點了
下面就是我的代碼實現了
private ExecutorService executorService;//定義一個線程池
定義線程池的大小
executorService=Executors.newFixedThreadPool(5);//開啟5個線程,其實根據你的情況,一般不會超過8個
線程啟動
executorService.execute(new Runnable() { @Override public void run() { getImageromSdk(); } }); 最后就是批量上傳圖片的方法了
public void getImageromSdk(){ Log.i("進入獲取圖片方法", "進入獲取圖片方法"); try{ String srcUrl = "/sdcard/"; //路徑 String fileName = "1.png"; //文件名 String filrName2="2.jpg";//文件名 List<String>imageList=new ArrayList<>();//定義一個list,里面裝2個圖片地址,模擬批量上傳 imageList.add(fileName); imageList.add(filrName2); for (int i = 0; i < imageList.size(); i++) { FileInputStream fis = new FileInputStream(srcUrl + imageList.get(i)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int count = 0; while((count = fis.read(buffer)) >= 0){ baos.write(buffer, 0, count); } String uploadBuffer = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT)); //進行Base64編碼 String methodName = "uploadImage"; getImageFromAndroid(methodName,imageList.get(i), uploadBuffer); //調用webservice Log.i("connectWebService", "start"); fis.close(); } }catch(Exception e){ e.printStackTrace(); } } 最后就是提交soap方法了,這方法我都寫了幾百遍了
public String getImageFromAndroid(String arg0,String arg1, String arg2){ Log.i("進入端口方法", "進入端口方法"); final String methodName="getImageFromAndroid"; final String soapAction=AgbcApi.NAMESPACE+methodName; request = new SoapObject(AgbcApi.NAMESPACE, methodName); request.addProperty("arg0",arg1); request.addProperty("arg1",arg2); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); (new MarshalBase64()).register(envelope); envelope.bodyOut = request; envelope.dotNet=false; envelope.setOutputSoapObject(request); HttpTransportSE ht = new HttpTransportSE(AgbcApi.TASKSERVICEURL); ht.debug=true; try { ht.call(soapAction, envelope); Log.i("請求", envelope.bodyIn.toString()); } catch (IOException | XmlPullParserException e) { e.printStackTrace(); } return arg1; }; 配置類
public class AgbcApi { /** * 服務器ip */ private static String IP="http://10.123.42.138:8080/fff"; public static String TASKSERVICEURL=IP+"TaskService"; public static String NAMESPACE="http://iservice.gbc.com/"; } 其實Android開發還是很簡單的只要你刻苦的去敲,多想想開發思路,多了解開發api有一天你會發現自己很牛逼,哈哈
新聞熱點
疑難解答