About Android calling C # WebService upload picture problem (do not use KSOAP2)

Source: Internet
Author: User
Tags soap set time vps

============ Problem Description ============


Younger brother beginner Android development. Recently need to do a picture upload function.
I was using Java to develop Android, calling C # WebService. Find a lot of information on the Internet, almost all with ksoap2 bag.
Please note that what I want to do is not ksoap the package.
My current method is to read from the Android to the image to be uploaded, with Base64 encoded into a byte stream string, by calling WebService the string as a parameter to the server side, the service side decoding the string, and finally saved to the corresponding path. The key to the entire upload process is data transfer in a byte stream string.
The function code is as follows:

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   "Upload pictures successfully!"  +  "Picture path:"  + toDir;             }            catch  (Exception e)             {             }             return  "Upload picture Failed! ";         }

Android: Calling the WebService method
public class Uploadutil {private static Httpconnsoap Soap = new Httpconnsoap ();p ublic static void Uploadimage (String filen Ame, 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 {/** *  gets the returned InputStream, which is not parsed within the method in order to enhance commonality.  *  *  @param  methodName *             webservice method name  *  @param  Parameters *             webservice method corresponding parameter name  *  @param  ParValues *   Values for parameters in the           webservice method  *  @return   Unresolved Inputstream */public inputstream getwebservre (string methodname, arraylist< string> parameters, arraylist<string> parvalues)  {//  Specify the URL address, I use constants here. string serverurl =  "Http://www.bsri.com.cn:99/ws3/Service1.asmx";// soapaction =   Namespace  +  method name string soapaction =  "http://tempuri.org/"  + methodname;//   Patchwork 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 ();             //sets the parameter for the method to. Net Parameter names in the  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;//  All of the data on it is pieced together requestdata, that is, the data sent to the server Try {url url = new url (ServerURL); //  Specify server address httpurlconnection con =  (httpurlconnection)  url.openconnection ();//  open link byte[]  bytes = requestdata.getbytes ("Utf-8"); //  Specify the encoding format, can solve the problem of Chinese garbled con.setdoinput (true);  //  Specifies whether the link can be entered Con.setdooutput(true); //  Specifies whether the link can output Con.setusecaches (false); //  Specifies whether the link is used only with cachescon.setconnecttimeout ( 6000); //  set time-out Con.setrequestmethod ("post"); //  Specify the method name to send, including POST and get. Con.setrequestproperty ("Content-type",  "Text/xml;charset=utf-8"); //  Set (Sent) content type Con.setrequestproperty ("SOAPAction",  soapaction); //  Specify Soapactioncon.setrequestproperty ("Content-length",  ""  + bytes.length); //  specified content length//   Send data Outputstream outstream = con.getoutputstream (); outstream.write (bytes); Outstream.flush (); Outstream.close ();//  obtain data// 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;}}

Trigger Upload Method:
@Overridepublic  void onclick (view v)  {switch  (V.getid ())  {case  r.id.selectimage:/*** *  This is called Android built-in Intent, to filter the image file &nbsp, but also can filter other  */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,  "Please select the picture! ",  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&NBSP;==&NBSP;ACTIVITY.RESULT_OK)  {/** *  when the selected picture is not empty, The way to get to the picture  */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); //  picture file path imgname = cursor.getstring (3);  //  picture filename 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 ();p hotodata = base64.encodetostring (bytes,  Base64.default);}  else {alerT ();}}  else {alert ();}}  catch  (exception e)  {}}super.onactivityresult (requestcode, resultcode, data);}

I feel there is no problem in theory, but actually, when executing to call WebService, when stitching requests, TS = new String ("<" + TPS + ">" + VPS + "</" + TPS + ">"); The picture-to-Base64 encoded string string is too long to cause memory overflow.
How to solve, hope you great God advice! Or something wrong with the program, ask the gods to point it out, or teach me the right way. I don't have much of a brother, please forgive me.

============ Solution 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&nbSP; (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 encoding} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} return fileStream;}


Submit using Post

About Android calling C # WebService upload picture problem (do not use KSOAP2)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.