andorid 平台调用Web Service , 图片传输

时间:2021-02-14 13:52:13

今天学习了下android调用web service,进行图片传输

下面是代码详解:

onActivityResult 方法在图片剪裁完成之后调用:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的
final Bitmap photo = data.getParcelableExtra("data"); //获取剪裁后的图片 try{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytes = baos.toByteArray(); //把图片变成byte数组 //下面的代码我也不太明白什么意思,好像在4.1主线程直接访问web service的时候会报异常 ,
//从Android 2.3开始提供了一个新的类StrictMode,可以帮助开发者改进他们的Android应用,
//StrictMode可以用于捕捉发生在应用程序主线程中耗时的磁盘、网络访问或函数调用,可以帮助开发者使其改进程序,
//使主线程处理UI和动画在磁盘读写和网络操作时变得更平滑,避免主线程被阻塞,导致ANR窗口的发生。 //http://www.cnblogs.com/zelos/archive/2011/02/27/1966403.html
//最后通过上面的url中的解决方案会编译报错,最后在网上找到了这个解决方案
Class<?> strictModeClass = Class.forName("android.os.StrictMode", true, Thread.currentThread()
.getContextClassLoader()); Class<?> threadPolicyClass = Class.forName("android.os.StrictMode$ThreadPolicy", true, Thread
.currentThread().getContextClassLoader()); Class<?> threadPolicyBuilderClass = Class.forName("android.os.StrictMode$ThreadPolicy$Builder", true,
Thread.currentThread().getContextClassLoader()); Method setThreadPolicyMethod = strictModeClass.getMethod("setThreadPolicy", threadPolicyClass); Method detectAllMethod = threadPolicyBuilderClass.getMethod("detectAll");
Method penaltyMethod = threadPolicyBuilderClass.getMethod("penaltyLog");
Method buildMethod = threadPolicyBuilderClass.getMethod("build"); Constructor<?> threadPolicyBuilderConstructor = threadPolicyBuilderClass.getConstructor();
Object threadPolicyBuilderObject = threadPolicyBuilderConstructor.newInstance(); Object obj = detectAllMethod.invoke(threadPolicyBuilderObject); obj = penaltyMethod.invoke(obj);
Object threadPolicyObject = buildMethod.invoke(obj);
setThreadPolicyMethod.invoke(strictModeClass, threadPolicyObject);
//------------ //把byte通过Base64变成字符串,通过web service 传送
String imgStream = Base64.encodeToString(bytes, 100);
CallWebService(imgStream);
}
catch(Exception ex)
{
Log.e("error:", ex.toString());
}
ImageView img = (ImageView)findViewById(R.id.imgView);
img.setImageBitmap(photo); System.out.println("set new photo");
break;
}
case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
final Bitmap photo = data.getParcelableExtra("data");
doCropPhoto(photo);
break;
}
}
}

下面是访问web service的代码:

    // 命名空间
String nameSpace = "http://192.168.1.110:800/";
// 调用的方法名称
String methodName = "GetFile";
// EndPoint
String endPoint = "http://192.168.1.110:800/WebService1.asmx";
// SOAP Action
String soapAction = "http://192.168.1.110:800/GetFile"; private void CallWebService(String imageStream) {
try {
// 通过soap访问web service
SoapObject soapObject = new SoapObject(nameSpace, methodName);
soapObject.addProperty("imgStream", imageStream); //设置参数 SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11); //构造SOAP协议的版本号,该版本号需要根据服务端WebService的版本号设置
envelope.bodyOut = soapObject;//该属性的值是创建的SoapObject对象。
envelope.dotNet = true; HttpTransportSE ht=new HttpTransportSE(endPoint);
ht.debug = true;
ht.call(soapAction, envelope); //第2个参数是创建的SoapSerializationEnvelope对象 if(envelope.getResponse()!=null)
{
SoapObject soapResult =(SoapObject) envelope.getResponse(); //使用getResponse方法获得WebService方法的返回结果
String result = soapResult.getProperty(0).toString();
          Toast.makeText(getApplicationContext(), "img Name:"+result,
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}

上面的是 android客户端的代码,下面的是web service中的代码

 [WebService(Namespace = "http://192.168.1.110:800/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string GetFile(string imgStream)
{
if (string.IsNullOrEmpty(imgStream))
{
return "false";
}
try
{
byte[] buffer = Convert.FromBase64String(imgStream);
MemoryStream ms = new MemoryStream(buffer);
string fileName = GenderImgFileName();
System.Drawing.Image.FromStream(ms).Save(@"d:\" + fileName);
return fileName;
}
catch (Exception)
{
return "false";
}
} private string GenderImgFileName()
{
return DateTime.Now.ToString("yyyy-MM-dd") + Guid.NewGuid() + ".jpg";
}

上面的就完成了。

C#中byte[] 和 Base64 之间的转换:

{    
string factString = "*";
byte[] myByte;
string Base64Str;
//先把字符串按照utf-8的编码转换成byte[]
Encoding myEncoding = Encoding.GetEncoding("utf-8");
//myByte中获得这样的字节数组:228,184,173,229,141,142,228,186,186,230,176,145,229,133,177,229,146,140,229,155,189
myByte = myEncoding.GetBytes(factString);
//把byte[]转成base64编码,这个例子形成的base64编码的unicode等价字符串为:"5Lit5Y2O5Lq65rCR5YWx5ZKM5Zu9"
Base64Str = Convert.ToBase64String(myByte);
//再从base64编码转成byte[],又恢复为字节数组:228,184,173,229,141,142,228,186,186,230,176,145,229,133,177,229,146,140,229,155,189
myByte = Convert.FromBase64String(Base64Str);
//用同一个Encoding对象把byte[]转成字符串:"*"
factString = myEncoding.GetString(myByte);
Console.WriteLine(factString);
}
原文地址:http://www.cnblogs.com/chnking/archive/2007/08/12/852669.html

android中Bitmap,byte[] 和Drawable相关的转换:http://www.cnblogs.com/fighter/archive/2012/02/20/android-bitmap-drawable.html

final Bitmap photo = data.getParcelableExtra("data");  
                
                try{
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    photo.compress(Bitmap.CompressFormat.PNG, 100, baos);
                    byte[] bytes =  baos.toByteArray();

Class<?> strictModeClass = Class.forName("android.os.StrictMode", true, Thread.currentThread()
                            .getContextClassLoader());

Class<?> threadPolicyClass = Class.forName("android.os.StrictMode$ThreadPolicy", true, Thread
                            .currentThread().getContextClassLoader());

Class<?> threadPolicyBuilderClass = Class.forName("android.os.StrictMode$ThreadPolicy$Builder", true,
                            Thread.currentThread().getContextClassLoader());

Method setThreadPolicyMethod = strictModeClass.getMethod("setThreadPolicy", threadPolicyClass);

Method detectAllMethod = threadPolicyBuilderClass.getMethod("detectAll");
                    Method penaltyMethod = threadPolicyBuilderClass.getMethod("penaltyLog");
                    Method buildMethod = threadPolicyBuilderClass.getMethod("build");

Constructor<?> threadPolicyBuilderConstructor = threadPolicyBuilderClass.getConstructor();
                    Object threadPolicyBuilderObject = threadPolicyBuilderConstructor.newInstance();

Object obj = detectAllMethod.invoke(threadPolicyBuilderObject);

obj = penaltyMethod.invoke(obj);
                    Object threadPolicyObject = buildMethod.invoke(obj);
                    setThreadPolicyMethod.invoke(strictModeClass, threadPolicyObject);
                    
                    String imgStream = Base64.encodeToString(bytes, 100);
                    CallWebService(imgStream);
                }
                catch(Exception ex)
                {
                    Log.e("error:", ex.toString());
                }
                ImageView img = (ImageView)findViewById(R.id.imgView);
                img.setImageBitmap(photo);