1. 程式人生 > >POST以流的方式傳送檔案

POST以流的方式傳送檔案

public static void postUpload(String json, String pwd,String targetFile) throws Exception{
		HttpClient httpclient = new DefaultHttpClient();  
		//請求處理頁面  
		HttpPost httppost = new HttpPost(  
		        "http://10.2.5.162:8081/Default.aspx");  
		//建立待處理的檔案  
		FileBody file = new FileBody(new File(targetFile));  
		//建立待處理的表單域內容文字  
		StringBody descript = new StringBody(json);  
		StringBody des= new StringBody(pwd);  
		//對請求的表單域進行填充  
		MultipartEntity reqEntity = new MultipartEntity();  
		reqEntity.addPart("file", file);  
		reqEntity.addPart("json", descript);
		reqEntity.addPart("password", des);  
		//設定請求  
		httppost.setEntity(reqEntity);  
		//執行  
		HttpResponse response = httpclient.execute(httppost);  
		//HttpEntity resEntity = response.getEntity();  
		//System.out.println(response.getStatusLine());  
		if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){  
		    HttpEntity entity = response.getEntity();  
		    //顯示內容  
		    if (entity != null) {  
		        System.out.println(EntityUtils.toString(entity));  
		    }  
		    if (entity != null) {  
		        entity.consumeContent();  
		    }  
		}  
	}