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如下:

package com.example.http ;

import java.io.File ;

import org.apache.commons.httpclient.HttpClient ;
import org.apache.commons.httpclient.HttpStatus ;
import org.apache.commons.httpclient.methods.PostMethod ;
import org.apache.commons.httpclient.methods.multipart.FilePart ;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity ;
import org.apache.commons.httpclient.methods.multipart.Part ;

public class Hclient

 {
 /*
  * private Context mContext ;
  *
  * public Hclient ( Context c ) { this.mContext = c ; }
  */

 public void UpLoadFile ( String str)
  {

   String targetURL = null ;// TODO 指定URL
   File targetFile = null ;// TODO 指定上传文件
   targetFile = new File ( str) ;
   targetURL = "http://192.168.1.100:8081/http/Http" ; // servleturl
   PostMethod filePost = new PostMethod ( targetURL ) ;
   try
    {
     // 通过以下方法可以模拟页面参数提交
     // filePost.setParameter("name", "中文");
     // filePost.setParameter("pass", "1234");
     Part [ ] parts =
      { new FilePart ( targetFile.getName ( ) , targetFile ) } ;
     filePost.setRequestEntity ( new MultipartRequestEntity (
            parts , filePost.getParams ( ) ) ) ;
     HttpClient client = new HttpClient ( ) ;
     client.getHttpConnectionManager ( ).getParams ( )
            .setConnectionTimeout ( 5000 ) ;
     int status = client.executeMethod ( filePost ) ;
     if ( status == HttpStatus.SC_OK )
      {
       System.out.println ( "上传成功" ) ;
       // 上传成功
      }
     else
      {
       System.out.println ( "上传失败" ) ;
       // 上传失败
      }
    }
   catch ( Exception ex )
    {
     ex.printStackTrace ( ) ;
    }
   finally
    {
     filePost.releaseConnection ( ) ;

    }
  }
 }

  • 1
  • 2
  • 3
  • 下一页

相关内容

    暂无相关文章