閱讀876 返回首頁    go 阿裏雲 go 技術社區[雲棲]


httpclient通過POST來上傳文件,而不是通過流的形式,並在服務端進行解析(通過httpmime.jar來操作)

1. 首先需要對應的JAR包 導入 httpmime-4.1.1.jar。

package url;

import io.IoStreamUtil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * httpclient上傳文件
 * @author linwei
 *
 */
public class MultipartEntityUtil {

	public static String postFile(File file,String url) throws ClientProtocolException, IOException {

		FileBody bin = null;
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);
		if(file != null) {
			bin = new FileBody(file);
		}

		StringBody username = new StringBody("13696900475");
		StringBody password = new StringBody("13696900475");
//請記住,這邊傳遞漢字會出現亂碼,解決方法如下,設置好編碼格式就好
                //new StringBody("漢字",Charset.forName("UTF-8")));  
		
	    MultipartEntity reqEntity = new MultipartEntity();
	    reqEntity.addPart("username", username);
	    reqEntity.addPart("password", password);
	    reqEntity.addPart("data", bin);
	    
	    httppost.setEntity(reqEntity);
	    System.out.println("執行: " + httppost.getRequestLine());
	    
	    HttpResponse response = httpclient.execute(httppost);
	    System.out.println("statusCode is " + response.getStatusLine().getStatusCode());
	    HttpEntity resEntity = response.getEntity();
	    System.out.println("----------------------------------------");
	    System.out.println(response.getStatusLine());
	    if (resEntity != null) {
	      System.out.println("返回長度: " + resEntity.getContentLength());
	      System.out.println("返回類型: " + resEntity.getContentType());
	      InputStream in = resEntity.getContent();
	      System.out.println("in is " + in);
	      System.out.println(IoStreamUtil.getStringFromInputStream(in));
	    }
	    if (resEntity != null) {
	      resEntity.consumeContent();
	    }
		return null;
	}
	
	public static void main(String[] args) throws ClientProtocolException, IOException {
	
		File file = new File("d:/rss.xml");
		String url = "https://localhost:8080/webtest/servlet/URLTest";
		postFile(file,url);
	}
	
}
  

2. 服務端的接收解析代碼(同樣的,服務端也需要導入上麵提到的JAR包) (特別注釋:在servlet中直接獲取的request是可以正常解析的,但是,在ACTION中獲取的request則是通過ACTION內部的類進行了封裝,因此,在ACTION中執行以下代碼,upload.parseRequest(request)方法執行返回的是空的,暫沒找到解決辦法。)

//commons-fileupload.jar  commons-io 
request.setCharacterEncoding("UTF-8");
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
          FileItemFactory factory = new DiskFileItemFactory();  
            ServletFileUpload upload = new ServletFileUpload(factory);  
            try {   
                List items = upload.parseRequest(request);  
                Iterator iter = items.iterator();  
                while (iter.hasNext()) {  
                    FileItem item = (FileItem) iter.next();  
                    if (item.isFormField()) {  
                        //普通文本信息處理  
                        String paramName = item.getFieldName();  
                        String paramValue = item.getString();  
                        System.out.println(paramName + ":" + paramValue);  
                    } else {  
                        //上傳文件信息處理  
                        String fileName = item.getName();  
                        byte[] data = item.get();  
                        String filePath = "d:/ssssss.txt";  
                        FileOutputStream fos = new FileOutputStream(filePath);  
                        fos.write(data);  
                        fos.close();  
                    }  
                }   
            } catch (FileUploadException e) {  
                e.printStackTrace();  
            }  
        }  


最後更新:2017-04-03 20:19:50

  上一篇:go 我的iOS視頻開放了,歡迎大家在線觀看
  下一篇:go 進程通信係列-消息緩衝