android调用.net webservice上传图片问题

huiyan1023 发布于 2012/08/17 12:19
阅读 5K+
收藏 0
android程序代码:
package com.example.uploadimage;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import org.kobjects.base64.Base64;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class UploadImageActivity extends Activity {
public static final String IMAGE_UNSPECIFIED = "image/*";
private static final String NAMESPACE = "http://tempuri.org/";
private static String URL = "http://192.168.2.100:1111/Service1.asmx";//
private static final String METHOD_NAME = "FileUploadImage";
private static String SOAP_ACTION = "http://tempuri.org/FileUploadImage";
TextView t1 =null;
Button button=null;
ImageView image = null;
private SoapObject soapObject;
@Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.penaltyLog()
.penaltyDeath()
.build());
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t1 =(TextView) findViewById(R.id.t1);
image = (ImageView)this.findViewById(R.id.image );
button =(Button)findViewById(R.id.button);
button.setOnClickListener(new WebOnclick());
}
class WebOnclick implements OnClickListener {
@Override
public void onClick(View v) {
System.out.println("as");
SoapObject aa;
if(testUpload())
t1.setText("成功!");
else
t1.setText("失败!");

}
}
@SuppressWarnings("resource")
@SuppressLint("SdCardPath")
public Boolean testUpload(){
try{
String srcUrl = "/mnt/sdcard/";
String fileName = "19.jpg";
FileInputStream fis = new FileInputStream(srcUrl + fileName);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int count = 0;
while((count = fis.read(buffer)) >= 0){
baos.write(buffer, 0, count);
}
String uploadBuffer = new String(Base64.encode(baos.toByteArray())); //进行Base64编码
if(connectWebService(uploadBuffer))
{
System.out.println("haha");
return true;
}
Log.i("connectWebService", "start");
fis.close();
}catch(Exception e){
e.printStackTrace();
}
return false;
}
private Boolean connectWebService(String uploadBuffer){
SoapObject soapObject = new SoapObject(NAMESPACE, METHOD_NAME);
soapObject.addProperty("title",1);
soapObject.addProperty("contect",1);
soapObject.addProperty("bytestr", uploadBuffer);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(soapObject);
envelope.bodyOut = soapObject;
envelope.dotNet = true;
envelope.encodingStyle = SoapSerializationEnvelope.ENC;
@SuppressWarnings("deprecation")
HttpTransportSE httpTranstation = new HttpTransportSE (URL);
try {
httpTranstation.call(SOAP_ACTION, envelope);
System.out.println("成功!");
return true;
/*Object result = envelope.getResponse();
Log.i("connectWebService", result.toString());
if(result.toString()=="文件上传成功")
return true;
else
return false;*/
} catch (Exception e) {
System.out.println("失败!");
System.out.println(e);
e.printStackTrace();
}
return false;
//return soapObject;
}
}
webservice代码:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.IO;
using System.Drawing;
namespace WebService1
{
/// <summary>
/// Service1 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World,调用成功!";
}
[WebMethod]
public string FileUploadImage(string bytestr)
{
if (bytestr.Trim() =="")
{
return "文件上传失败!";
}
string name = "";
string mess = "";
try
{
// Random random = new Random();
//string i = random.Next(0, 10000000).ToString();
name = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
bool flag = StringToFile(bytestr, Server.MapPath("image\\") + "" + name + ".jpg");
string filePath = "/image/" + name + ".jpg";
}
catch (Exception ex)
{
mess = ex.Message;
}
if (mess != "")
{
return mess;
}
else
{
return "文件上传成功";
}
}
protected System.Drawing.Image Base64StringToImage(string strbase64)
{
try
{
byte[] arr = Convert.FromBase64String(strbase64);
MemoryStream ms = new MemoryStream(arr);
//Bitmap bmp = new Bitmap(ms);
ms.Write(arr, 0, arr.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
ms.Close();
return image;
//return bmp;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 把经过base64编码的字符串保存为文件
/// </summary>
/// <param name="base64String">经base64加码后的字符串 </param>
/// <param name="fileName">保存文件的路径和文件名 </param>
/// <returns>保存文件是否成功 </returns>
public static bool StringToFile(string base64String, string fileName)
{
//string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + @"/beapp/" + fileName;
System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
if (!string.IsNullOrEmpty(base64String) && File.Exists(fileName))
{
bw.Write(Convert.FromBase64String(base64String));
}
bw.Close();
fs.Close();
return true;
}
}
}
android程序原本是用2.版本开发的,但是在连接webservice的时候出现异常:android.os.NetWorkOnMainThreadException
后来在网上找到答案,用2.3版本在onCreate()下加上一些代码后,在测试的时候程序没法正常运行,请各位巴士帮忙看看吧,急用
加载中
0
y
yytandlsl
android3.0以后访问网络得放在新的线程里面
返回顶部
顶部