httpclient4.5 上傳帶有中文的文件亂碼

public static String postUpload(String url, String fileField, String fileRealPath, 
			Map<String,String> params, Map<String,String> headerMap){
		HttpPost httppost = new HttpPost(url);
		MultipartEntityBuilder meb = MultipartEntityBuilder.create();
		meb.setCharset(Charset.forName("utf-8"));  
		meb.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);  
		FileBody fileBody = new FileBody(new File(fileRealPath));
		meb.addPart(fileField, fileBody);//添加文件
		if(null != params){
			//添加map中參數
			Set<String> keySet = params.keySet();
			for(String key : keySet){
				StringBody contentBody = new StringBody(params.get(key), ContentType.TEXT_PLAIN);
				meb.addPart(key, contentBody);
			}
			HttpEntity reqEntity = meb.build();
			httppost.setEntity(reqEntity);
		}
		return excuteRequest(httppost, headerMap);
	}

方法一:java

加上這兩行代碼app

meb.setCharset(Charset.forName("utf-8"));  
meb.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);  post

方法二:(還沒試,應該可行)ui

對包含中文路徑url進行編碼後在傳編碼

方法一和方法二都要在接收接收文件那邊對文件名進行url解碼url

url編碼和解密方法code

/**
	 * 將URL中含有的中文轉換爲ascii;
	 * 例:"中文亂碼" 轉換爲 "%E4%B8%AD%E6%96%87%E4%B9%B1%E7%A0%81"
	 * utf8URL編碼
	 * @param text
	 * @return
	 */
	public static String utf8UrlEncode(String text){
		StringBuffer result=new StringBuffer();
		for(int i=0;i<text.length();i++){
			char c=text.charAt(i);
			if(c>=0 && c<=255)
				result.append(c);
			else{
				byte[] b=new byte[0];
				try {
					b=Character.toString(c).getBytes("UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				for(int j=0;j<b.length;j++){
					int k=b[j];
					if(k<0)
						k+=256;
					result.append("%"+Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return result.toString().replaceAll(" ","%20");		
	}
	
	/**
	 * 將URL的中亂碼(ascii碼)轉換爲中文的URL
	 * 例: "%E4%B8%AD%E6%96%87%E4%B9%B1%E7%A0%81" 轉換爲"中文亂碼"
	 * @param text
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String utf8UrlDecoder(String text) throws UnsupportedEncodingException{
		return URLDecoder.decode(text, "utf-8");
	}
相關文章
相關標籤/搜索