歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

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 ( ) ;

    }
  }
 }

Copyright © Linux教程網 All Rights Reserved