關於安卓調用C#的WebService上傳圖片問題(不使用ksoap2)

來源:互聯網
上載者:User

標籤:des   android   http   io   os   ar   使用   java   for   

============問題描述============


小弟初學安卓開發。最近需要做一個圖片上傳的功能。
我是用java開發安卓,調用C#的WebService。在網上找到一大堆資料,幾乎全部是用ksoap2包的。
請注意,我想做的是不用ksoap包的。
我現在的方法是從android端用讀取到要上傳的圖片,用Base64編碼成位元組流的字串,通過調用webservice把該字串作為參數傳到伺服器端,服務端解碼該字串,最後儲存到相應的路徑下。整個上傳過程的關鍵就是以位元組流的字串進行資料傳遞。
功能代碼如下:

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 "上傳圖片失敗!";        }

安卓端:調用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,為了增強通用性,在方法內不對其進行解析。 *  * @param methodName *            webservice方法名 * @param Parameters *            webservice方法對應的參數名 * @param ParValues *            webservice方法中參數對應的值 * @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();            //設定該方法的參數為.net webService中的參數名稱            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;// 其上所有的資料都是在拼湊requestData,即向伺服器發送的資料try {URL url = new URL(ServerUrl); // 指定伺服器位址HttpURLConnection con = (HttpURLConnection) url.openConnection();// 開啟連結byte[] bytes = requestData.getBytes("utf-8"); // 指定編碼格式,可以解決中文亂碼問題con.setDoInput(true); // 指定該連結是否可以輸入con.setDoOutput(true); // 指定該連結是否可以輸出con.setUseCaches(false); // 指定該連結是否只用cachescon.setConnectTimeout(6000); // 設定逾時時間con.setRequestMethod("POST"); // 指定發送方法名,包括Post和Get。con.setRequestProperty("Content-Type", "text/xml;charset=utf-8"); // 設定(發送的)內容類型con.setRequestProperty("SOAPAction", soapAction); // 指定soapActioncon.setRequestProperty("Content-Length", "" + bytes.length); // 指定內容長度// 發送資料OutputStream outStream = con.getOutputStream();outStream.write(bytes);outStream.flush();outStream.close();// 擷取資料// 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("&lt;", "<");String newS1 = newS.replaceAll("&gt;", ">");ByteArrayInputStream bais = new ByteArrayInputStream(newS1.getBytes());return bais;} catch (Exception e) {e.printStackTrace();return null;}}}

觸發上傳方法:
@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.selectImage:/*** * 這個是調用android內建的intent,來過濾圖片檔案 ,同時也可以過濾其他的 */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) {/** * 當選擇的圖片不為空白的話,在擷取到圖片的途徑 */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);}

我感覺理論上是沒有什麼問題的,但是實際上,執行到調用WebService的時候,拼接請求時, ts = new String("<" + tps + ">" + vps + "</" + tps + ">");這裡可能是圖片轉base64編碼的String串長度太長,導致記憶體溢出。
如何解決,望各位大神指教!或者程式有什麼錯還請大神們指出,或者教我用合適的方法。小弟分不多,還請見諒。

============解決方案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)); // 進行Base64編碼} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return fileStream;}


使用post進行提交

關於安卓調用C#的WebService上傳圖片問題(不使用ksoap2)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.