关于安卓调用C#的WebService上传图片问题(不使用ksoap2)
生活随笔
收集整理的這篇文章主要介紹了
关于安卓调用C#的WebService上传图片问题(不使用ksoap2)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
============問題描述============
小弟初學(xué)安卓開發(fā)。最近需要做一個(gè)圖片上傳的功能。
我是用java開發(fā)安卓,調(diào)用C#的WebService。在網(wǎng)上找到一大堆資料,幾乎全部是用ksoap2包的。
請注意,我想做的是不用ksoap包的。
我現(xiàn)在的方法是從android端用讀取到要上傳的圖片,用Base64編碼成字節(jié)流的字符串,通過調(diào)用webservice把該字符串作為參數(shù)傳到服務(wù)器端,服務(wù)端解碼該字符串,最后保存到相應(yīng)的路徑下。整個(gè)上傳過程的關(guān)鍵就是以字節(jié)流的字符串進(jìn)行數(shù)據(jù)傳遞。
功能代碼如下:
WebService:public?string?uploadImage(string?filename,?string?image){FileStream?fs?=?null;try{string?toDir?=?"E:\\C#?Project\\Dev\\GPRSDataIn\\GPRSDataIn\\Images";fs?=?new?FileStream(filename,?FileMode.Create);byte[]?buffer?=?Encoding.UTF8.GetBytes(image);fs.Write(buffer,?0,?buffer.Length);fs.Flush();fs.Close();return?"上傳圖片成功!"?+?"圖片路徑為:"?+?toDir;}catch?(Exception?e){}return?"上傳圖片失敗!";}
安卓端:調(diào)用WebService方法
public?class?UploadUtil?{private?static?HttpConnSoap?Soap?=?new?HttpConnSoap();public?static?void?uploadImage(String?filename,?String?image)?{ArrayList<String>arrayList=new?ArrayList<String>();ArrayList<String>brrayList=new?ArrayList<String>();arrayList.clear();brrayList.clear();arrayList.add("filename");arrayList.add("image");brrayList.add(filename);brrayList.add(image);Soap.GetWebServre("uploadImage",?arrayList,?brrayList);}}
public?class?HttpConnSoap?{/***?獲取返回的InputStream,為了增強(qiáng)通用性,在方法內(nèi)不對其進(jìn)行解析。*?*?@param?methodName*????????????webservice方法名*?@param?Parameters*????????????webservice方法對應(yīng)的參數(shù)名*?@param?ParValues*????????????webservice方法中參數(shù)對應(yīng)的值*?@return?未解析的InputStream*/public?InputStream?GetWebServre(String?methodName,?ArrayList<String>?Parameters,?ArrayList<String>?ParValues)?{//?指定URL地址,我這里使用的是常量。String?ServerUrl?=?"http://www.bsri.com.cn:99/ws3/Service1.asmx";//?soapAction?=?命名空間?+?方法名String?soapAction?=?"http://tempuri.org/"?+?methodName;//?拼湊requestDataString?soap?=?"<?xml?version=\"1.0\"?encoding=\"utf-8\"?>"+?"<soap:Envelope?xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"?xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"?xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"+?"<soap:Body?/>";String?tps,vps,ts;String?mreakString?=?"";mreakString?=?"<"?+?methodName?+?"?xmlns=\"http://tempuri.org/\">";for?(int?i?=?0;?i?<?Parameters.size();?i++){tps?=?Parameters.get?(i).toString();//設(shè)置該方法的參數(shù)為.net?webService中的參數(shù)名稱vps?=?ParValues.get?(i).toString();ts?=?new?String("<"?+?tps?+?">"?+?vps?+?"</"?+?tps?+?">");mreakString?=?mreakString?+?ts;}mreakString?=?mreakString?+?"</"?+?methodName?+?">";String?soap2?=?"</soap:Envelope>";String?requestData?=?soap?+?mreakString?+?soap2;//?其上所有的數(shù)據(jù)都是在拼湊requestData,即向服務(wù)器發(fā)送的數(shù)據(jù)try?{URL?url?=?new?URL(ServerUrl);?//?指定服務(wù)器地址HttpURLConnection?con?=?(HttpURLConnection)?url.openConnection();//?打開鏈接byte[]?bytes?=?requestData.getBytes("utf-8");?//?指定編碼格式,可以解決中文亂碼問題con.setDoInput(true);?//?指定該鏈接是否可以輸入con.setDoOutput(true);?//?指定該鏈接是否可以輸出con.setUseCaches(false);?//?指定該鏈接是否只用cachescon.setConnectTimeout(6000);?//?設(shè)置超時(shí)時(shí)間con.setRequestMethod("POST");?//?指定發(fā)送方法名,包括Post和Get。con.setRequestProperty("Content-Type",?"text/xml;charset=utf-8");?//?設(shè)置(發(fā)送的)內(nèi)容類型con.setRequestProperty("SOAPAction",?soapAction);?//?指定soapActioncon.setRequestProperty("Content-Length",?""?+?bytes.length);?//?指定內(nèi)容長度//?發(fā)送數(shù)據(jù)OutputStream?outStream?=?con.getOutputStream();outStream.write(bytes);outStream.flush();outStream.close();//?獲取數(shù)據(jù)//?con.connect();BufferedInputStream?ois?=?new?BufferedInputStream(con.getInputStream());byte[]?revBytes?=?new?byte[20480];ois.read(revBytes);//InputStream?inputStream?=?new?ByteArrayInputStream(revBytes);String?s?=?new?String(revBytes);String?newS?=?s.replaceAll("<",?"<");String?newS1?=?newS.replaceAll(">",?">");ByteArrayInputStream?bais?=?new?ByteArrayInputStream(newS1.getBytes());return?bais;}?catch?(Exception?e)?{e.printStackTrace();return?null;}}}
觸發(fā)上傳方法:
@Overridepublic?void?onClick(View?v)?{switch?(v.getId())?{case?R.id.selectImage:/***?*?這個(gè)是調(diào)用android內(nèi)置的intent,來過濾圖片文件?,同時(shí)也可以過濾其他的?*/Intent?intent?=?new?Intent();intent.setType("image/*");intent.setAction(Intent.ACTION_GET_CONTENT);startActivityForResult(intent,?1);break;case?R.id.uploadImage:if?(picPath?==?null)?{Toast.makeText(Upload.this,?"請選擇圖片!",?1000).show();}?else?{final?File?file?=?new?File(picPath);if?(file?!=?null)?{UploadUtil.uploadImage(imgName,?photodata);}}break;default:break;}}@Overrideprotected?void?onActivityResult(int?requestCode,?int?resultCode,?Intent?data)?{if?(resultCode?==?Activity.RESULT_OK)?{/**?*?當(dāng)選擇的圖片不為空的話,在獲取到圖片的途徑?*/Uri?uri?=?data.getData();try?{Cursor?cursor?=?getContentResolver().query(uri,?null,?null,null,?null);if?(cursor?!=?null)?{ContentResolver?cr?=?this.getContentResolver();cursor.moveToFirst();String?path?=?cursor.getString(1);?//?圖片文件路徑imgName?=?cursor.getString(3);?//?圖片文件名if?(path.endsWith("jpg")?||?path.endsWith("png"))?{picPath?=?path;Bitmap?bitmap?=?BitmapFactory.decodeStream(cr.openInputStream(uri));imageView.setImageBitmap(bitmap);FileInputStream?fis?=?new?FileInputStream(path);ByteArrayOutputStream?baos?=?new?ByteArrayOutputStream();byte[]?buffer?=?new?byte[20480];int?count?=?0;while?((count?=?fis.read(buffer))?>=?0)?{baos.write(buffer,?0,?count);}byte[]?bytes?=?baos.toByteArray();photodata?=?Base64.encodeToString(bytes,?Base64.DEFAULT);}?else?{alert();}}?else?{alert();}}?catch?(Exception?e)?{}}super.onActivityResult(requestCode,?resultCode,?data);}
我感覺理論上是沒有什么問題的,但是實(shí)際上,執(zhí)行到調(diào)用WebService的時(shí)候,拼接請求時(shí),?ts?=?new?String("<"?+?tps?+?">"?+?vps?+?"</"?+?tps?+?">");這里可能是圖片轉(zhuǎn)base64編碼的String串長度太長,導(dǎo)致內(nèi)存溢出。
如何解決,望各位大神指教!或者程序有什么錯(cuò)還請大神們指出,或者教我用合適的方法。小弟分不多,還請見諒。
============解決方案1============
void?submieGson(String?users){try?{HttpClient?httpClient?=?new?DefaultHttpClient();HttpPost?httppost?=?new?HttpPost("http://*/jsonws/frank/ftocservice/getUserInfo");List<NameValuePair>?nameValuePairs?=?new?ArrayList<NameValuePair>();nameValuePairs.add(new?BasicNameValuePair("users",?users));nameValuePairs.add(new?BasicNameValuePair("file",?getFileString()));httppost.setEntity(new?UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));HttpResponse?response?=?httpClient.execute(httppost);System.out.println("rescode?="+response.getStatusLine().getStatusCode());if?(response.getStatusLine().getStatusCode()?==?200)?{String?str?=?EntityUtils.toString(response.getEntity(),"utf-8");System.out.println("json?========"+str);Message?msg?=?Message.obtain();msg.obj?=?str;mHandler.sendMessage(msg);}}?catch?(Exception?e)?{e.printStackTrace();}}
String?getFileString()?{String?fileStream?=?null;FileInputStream?fis;try?{fis?=?new?FileInputStream(Environment.getExternalStorageDirectory().getPath()?+?"/QuickCheck/image/temp.png");ByteArrayOutputStream?baos?=?new?ByteArrayOutputStream();byte[]?buffer?=?new?byte[1024];int?count?=?0;while?((count?=?fis.read(buffer))?>=?0)?{baos.write(buffer,?0,?count);}fis.close();fileStream?=?new?String(Base64.encode(baos.toByteArray(),Base64.DEFAULT));?//?進(jìn)行Base64編碼}?catch?(FileNotFoundException?e)?{e.printStackTrace();}?catch?(IOException?e)?{e.printStackTrace();}return?fileStream;}
使用post進(jìn)行提交
轉(zhuǎn)載于:https://www.cnblogs.com/yiguobei99/p/4035828.html
總結(jié)
以上是生活随笔為你收集整理的关于安卓调用C#的WebService上传图片问题(不使用ksoap2)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 黑马程序员——OC语言基本语法知识(一)
- 下一篇: CImage 是基于GDI+的,很老的一