android通过http传输文件到servlet

java.lang.NoClassDefFoundError代码部分来自网络,这里引用的是apache给的开源jar包,实现很方便的,(commons-httpclient-3.1android客户端使用),(commons-fileupload-1.2.2,commons-io-2.4,servlet的使用,记得把后面两个jar包放在 C:\Program Files\Java\jdk1.7.0_09\jre\lib\ext目录下)

下面贴贴代码吧:

httpclict如下:

[html]  view plain copy print ?
  1. package com.example.http ;  
  2.   
  3. import java.io.File ;  
  4.   
  5. import org.apache.commons.httpclient.HttpClient ;  
  6. import org.apache.commons.httpclient.HttpStatus ;  
  7. import org.apache.commons.httpclient.methods.PostMethod ;  
  8. import org.apache.commons.httpclient.methods.multipart.FilePart ;  
  9. import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity ;  
  10. import org.apache.commons.httpclient.methods.multipart.Part ;  
  11.   
  12. public class Hclient  
  13.   
  14.     {  
  15.     /*  
  16.      * private Context mContext ;  
  17.      *   
  18.      * public Hclient ( Context c ) { this.mContext = c ; }  
  19.      */  
  20.   
  21.     public void UpLoadFile ( String str)  
  22.         {  
  23.   
  24.             String targetURL = null ;// TODO 指定URL  
  25.             File targetFile = null ;// TODO 指定上传文件  
  26.             targetFile = new File ( str) ;  
  27.             targetURL = "http://192.168.1.100:8081/http/Http" ; // servleturl  
  28.             PostMethod filePost = new PostMethod ( targetURL ) ;  
  29.             try  
  30.                 {  
  31.                     // 通过以下方法可以模拟页面参数提交  
  32.                     // filePost.setParameter("name", "中文");  
  33.                     // filePost.setParameter("pass", "1234");  
  34.                     Part [ ] parts =  
  35.                         { new FilePart ( targetFile.getName ( ) , targetFile ) } ;  
  36.                     filePost.setRequestEntity ( new MultipartRequestEntity (  
  37.                             parts , filePost.getParams ( ) ) ) ;  
  38.                     HttpClient client = new HttpClient ( ) ;  
  39.                     client.getHttpConnectionManager ( ).getParams ( )  
  40.                             .setConnectionTimeout ( 5000 ) ;  
  41.                     int status = client.executeMethod ( filePost ) ;  
  42.                     if ( status == HttpStatus.SC_OK )  
  43.                         {  
  44.                             System.out.println ( "上传成功" ) ;  
  45.                             // 上传成功  
  46.                         }  
  47.                     else  
  48.                         {  
  49.                             System.out.println ( "上传失败" ) ;  
  50.                             // 上传失败  
  51.                         }  
  52.                 }  
  53.             catch ( Exception ex )  
  54.                 {  
  55.                     ex.printStackTrace ( ) ;  
  56.                 }  
  57.             finally  
  58.                 {  
  59.                     filePost.releaseConnection ( ) ;  
  60.   
  61.                 }  
  62.         }  
  63.     }  

Activity如下:


[html]  view plain copy print ?
  1. package com.example.http ;  
  2.   
  3. import android.app.Activity ;  
  4. import android.os.Bundle ;  
  5. import android.os.StrictMode ;  
  6. import android.view.View ;  
  7. import android.widget.Button ;  
  8.   
  9. public class HttpMainActivity extends Activity  
  10.     {  
  11.   
  12.         private Button  mButton ;  
  13.         private String  str1    = "/sdcard/http.txt" ;  
  14.         private String  str2    = "/sdcard/http.mp3" ;  
  15.         private int     mFlag   = 0 ;  
  16.         Hclient         hclient ;  
  17.   
  18.         @ Override  
  19.         protected void onCreate( Bundle savedInstanceState )  
  20.             {  
  21.                 super.onCreate ( savedInstanceState ) ;  
  22.                 StrictMode  
  23.                         .setThreadPolicy ( new StrictMode.ThreadPolicy.Builder ( )  
  24.                                 .detectDiskReads ( ).detectDiskWrites ( )  
  25.                                 .detectNetwork ( ).penaltyLog ( ).build ( ) ) ;  
  26.                 StrictMode.setVmPolicy ( new StrictMode.VmPolicy.Builder ( )  
  27.                         .detectLeakedSqlLiteObjects ( )  
  28.                         .detectLeakedClosableObjects ( ).penaltyLog ( )  
  29.                         .penaltyDeath ( ).build ( ) ) ;  
  30.                 setContentView ( R.layout.activity_http_main ) ;  
  31.                 mButton = ( Button ) findViewById ( R.id.button ) ;  
  32.                 hclient = new Hclient ( ) ;  
  33.                 mButton.setOnClickListener ( new View.OnClickListener ( )  
  34.                     {  
  35.   
  36.                         @ Override  
  37.                         public void onClick( View v )  
  38.                             {  
  39.                                 mFlag ++ ;  
  40.                                 if ( mFlag == 1 )  
  41.                                     {  
  42.                                         hclient.UpLoadFile ( str1 ) ;  
  43.                                     }  
  44.                                 else  
  45.                                     if ( mFlag == 2 )  
  46.                                         {  
  47.                                             hclient.UpLoadFile ( str2 ) ;  
  48.                                         }  
  49.                                     else  
  50.                                         {  
  51.   
  52.                                         }  
  53.                             }  
  54.                     } ) ;  
  55.             }  
  56.   
  57.     }  

记得加权限:

[html]  view plain copy print ?
  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  2. <uses-permission android:name="android.permission.INTERNET"/>  

t添加jar包的时候可能编译不过,java.lang.NoClassDefFoundError错误,下面给出办法:

1,添加jar包

2,把jar包放在libs文件中,如图


下面是servlet代码:

[html]  view plain copy print ?
  1. import java.io.File ;  
  2. import java.io.IOException ;  
  3. import java.util.Iterator ;  
  4. import java.util.List ;  
  5.   
  6. import javax.servlet.ServletException ;  
  7. import javax.servlet.http.HttpServlet ;  
  8. import javax.servlet.http.HttpServletRequest ;  
  9. import javax.servlet.http.HttpServletResponse ;  
  10.   
  11. import org.apache.commons.fileupload.FileItem ;  
  12. import org.apache.commons.fileupload.disk.DiskFileItemFactory ;  
  13. import org.apache.commons.fileupload.servlet.ServletFileUpload ;  
  14.   
  15. public class TestServlets extends HttpServlet  
  16.   
  17.     {  
  18.         private String  uploadPath  = "D:\\temp" ;              // 上传文件的目录  
  19.         private String  tempPath    = "d:\\temp\\buffer\\" ;    // 临时文件目录  
  20.         private File    tempPathFile ;  
  21.   
  22.         public void init( ) throws ServletException  
  23.             {  
  24.                 File uploadFile = new File ( uploadPath ) ;  
  25.                 if ( ! uploadFile.exists ( ) )  
  26.                     {  
  27.                         uploadFile.mkdirs ( ) ;  
  28.                     }  
  29.                 File tempPathFile = new File ( tempPath ) ;  
  30.                 if ( ! tempPathFile.exists ( ) )  
  31.                     {  
  32.                         tempPathFile.mkdirs ( ) ;  
  33.                     }  
  34.             }  
  35.   
  36.         public void doPost( HttpServletRequest request ,  
  37.                 HttpServletResponse response ) throws ServletException ,  
  38.                 IOException  
  39.             {  
  40.                 try  
  41.                     {  
  42.                         // Create a factory for disk-based file items  
  43.                         DiskFileItemFactory factory = new DiskFileItemFactory ( ) ;  
  44.                         // Set factory constraints  
  45.                         factory.setSizeThreshold ( 4096 ) ; // 设置缓冲区大小,这里是4kb  
  46.                         factory.setRepository ( tempPathFile ) ;// 设置缓冲区目录  
  47.                         // Create a new file upload handler  
  48.                         ServletFileUpload upload = new ServletFileUpload (  
  49.                                 factory ) ;  
  50.                         // Set overall request size constraint  
  51.                         upload.setSizeMax ( 4194304 ) ; // 设置最大文件尺寸,这里是4MB  
  52.                         List < FileItem > items = upload  
  53.                                 .parseRequest ( request ) ;// 得到所有的文件  
  54.                         Iterator < FileItem > i = items.iterator ( ) ;  
  55.                         while ( i.hasNext ( ) )  
  56.                             {  
  57.                                 FileItem fi = ( FileItem ) i.next ( ) ;  
  58.                                 String fileName = fi.getName ( ) ;  
  59.                                 if ( fileName != null )  
  60.                                     {  
  61.                                         File fullFile = new File (  
  62.                                                 fi.getName ( ) ) ;  
  63.                                         File savedFile = new File ( uploadPath ,  
  64.                                                 fullFile.getName ( ) ) ;  
  65.                                         fi.write ( savedFile ) ;  
  66.                                     }  
  67.                             }  
  68.                         System.out.print ( "upload succeed" ) ;  
  69.                     }  
  70.                 catch ( Exception e )  
  71.                     {  
  72.                         System.out.println ( e.getMessage ( ) ) ;  
  73.                         // 可以跳转出错页面  
  74.                         e.printStackTrace ( ) ;  
  75.                     }  
  76.             }  
  77.     }  


点击打开链接,点击这个是jar包的下载地址。


转自 http://blog.csdn.net/csh159/article/details/8521279


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值