老规矩废话不多说,直接入主题

注:wcf 使用rest风格,传递json数据,图片是经过base64编码,android 使用common-codec-1.5.jar 进行base64编码

服务器端

wcf接口:

namespace Test{    // 注意: 如果更改此处的接口名称 "IService1",也必须更新 Web.config 中对 "IService1" 的引用。    [ServiceContract]    public interface IService1    {              // 任务: 在此处添加服务操作        [OperationContract]        [WebInvoke(Method = "POST", UriTemplate = "update_pictrue",BodyStyle=WebMessageBodyStyle.WrappedRequest,RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json)]        string update_pictrue(string name, string content, string type);                [OperationContract]        [WebInvoke(Method = "POST", UriTemplate = "down_pictrue", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]        string down_pictrue(string name);    }}

接口实现:

namespace Test{    // 注意: 如果更改此处的类名“Service1”,也必须更新 Web.config 和关联的 .svc 文件中对“Service1”的引用。    public class Service1 : IService1    {               #region IService1 成员        public string update_pictrue(string name,string content, string type)        {           // throw new NotImplementedException();            if (type != ".jpg" && type != ".gif")            {                return "格式不正确";            }            else            {                string imgFilePath = @"F:\Wcf_teach\pictrue_update_down\Test\update_pictrue\" + name;                if (!File.Exists(imgFilePath))                {                    try                    {                        byte[] ms_content = Convert.FromBase64String(content);                        FileStream fs = File.Open(imgFilePath, FileMode.OpenOrCreate);                        fs.Write(ms_content, 0, ms_content.Length);                        fs.Close();                        return "上传成功";                    }                    catch (Exception ex)                    {                        return "出现异常";                    }                }                else                {                    return "上传失败";                }            }                  }        public string down_pictrue(string name)        {          //  throw new NotImplementedException();            string imgFilePath = @"F:\Wcf_teach\pictrue_update_down\Test\update_pictrue\" + name;            if (File.Exists(imgFilePath))            {                System.IO.FileStream fs = new System.IO.FileStream(imgFilePath, System.IO.FileMode.Open);                int i = (int)fs.Length;                byte[] content = new byte[i];                fs.Read(content, 0, i);                string result = Convert.ToBase64String(content);                fs.Close();                return result;                           }            else            {                throw new Exception("没有该文件出现异常");            }                  }        #endregion    }}

客户端

public class pictrue_update_down extends Activity {private Button update_btn;private Button down_btn;private ImageView img_img;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);findAll();bind();}public void findAll() {update_btn = (Button) this.findViewById(R.id.update_btn);down_btn = (Button) this.findViewById(R.id.down_btn);img_img = (ImageView) this.findViewById(R.id.img_img);}public void bind() {update_btn.setOnClickListener(mylistener);down_btn.setOnClickListener(mylistener);}private View.OnClickListener mylistener = new OnClickListener() {public void onClick(View v) {// TODO Auto-generated method stubswitch (v.getId()) {case R.id.update_btn:Thread th1 = new Thread(new mythread());th1.start();break;case R.id.down_btn:Thread th2 = new Thread(new mythread_down());th2.start();break;default:break;}}};Handler hd = new Handler() {@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stub// super.handleMessage(msg);if (msg.what == 123) {String jason = msg.obj.toString();String filepath = Environment.getExternalStorageDirectory()+ File.separator + jason;Bitmap bitmap1 = BitmapFactory.decodeFile(filepath);img_img.setImageBitmap(bitmap1);}}  };class mythread_down implements Runnable {public void run() {// TODO Auto-generated method stubHttpClient hc = new DefaultHttpClient();HttpPost hp = new HttpPost("http://192.168.1.229/Test/service1.svc/down_pictrue");HttpResponse hr = null;JSONObject jo1 = new JSONObject();try {jo1.put("name", "999.jpg");StringEntity se = new StringEntity(jo1.toString(), HTTP.UTF_8);se.setContentType("application/json");hp.setEntity(se);hr = hc.execute(hp);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}String strResp = null;if (hr.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {try {strResp = EntityUtils.toString(hr.getEntity());File f = new File("//sdcard//999.jpg");if (!f.exists()) {f.createNewFile();FileOutputStream fos=new FileOutputStream(f);byte[] content=  Base64.decodeBase64(strResp.getBytes());fos.write(content);fos.flush();Message msg=hd.obtainMessage(123);msg.obj="//sdcard//999.jpg";hd.sendMessage(msg);  }} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}else {Toast.makeText(pictrue_update_down.this, "下载失败",Toast.LENGTH_LONG).show();}}}class mythread implements Runnable {public void run() {// TODO Auto-generated method stubHttpClient hc = new DefaultHttpClient();HttpPost hp = new HttpPost("http://192.168.1.229/Test/service1.svc/update_pictrue");HttpResponse hr;String path = "//sdcard//999.jpg";File f = new File(path);if (f.exists()) {// System.out.println("successful");try {int ig = (int) f.length();byte[] content = new byte[ig];FileInputStream fis;fis = new FileInputStream(f);fis.read(content, 0, ig);String jason = new String(Base64.encodeBase64(content));JSONObject jo1 = new JSONObject();jo1.put("name", "999.jpg");jo1.put("content", jason);jo1.put("type", ".jpg");StringEntity se = new StringEntity(jo1.toString(),HTTP.UTF_8);se.setContentType("application/json");hp.setEntity(se);hr = hc.execute(hp);String strResp = null;if (hr.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {strResp = EntityUtils.toString(hr.getEntity());} else {strResp = "$no_found_date$";}Toast.makeText(pictrue_update_down.this, strResp,Toast.LENGTH_LONG).show();} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {hp.abort();}}}}}

更多相关文章

  1. android 新建项目中去掉标题栏
  2. Android(安卓)O指纹识别解析
  3. Android(安卓)AIDL使用详解 +整合应用
  4. Android(安卓)AIDL使用详解
  5. android ndk 调用第三方so
  6. 什么是AIDL
  7. Android(安卓)更改 Toast 的默认位置及自定义Toast
  8. android Java BASE64编码和解码二:图片的编码和解码
  9. Android开发者指南(12) ―― Android(安卓)Supported Media Form

随机推荐

  1. 安装android sdk 遇到几个问题
  2. Native+WebApp中Phonegap调用Android(安
  3. Android(安卓)很酷的天气动画控件
  4. android背景选择器selector用法
  5. Android(安卓)带百分比数字的水平、圆形
  6. Android屏幕保持常亮的三种方法
  7. Android(安卓)常用对话框Dialog封装
  8. Android简单自定义圆形和水平ProgressBar
  9. Android中RelativeLayout各个属性的含义
  10. Android之Drawerlayout——实现侧滑菜单