1. 程式人生 > >servlet和action中獲取URL中的漢字(解決URL中漢字為亂碼的問題)

servlet和action中獲取URL中的漢字(解決URL中漢字為亂碼的問題)

最近在專案中又遇到一個小問題,通過HttpURLConnection來傳遞漢字時,服務端獲取漢字引數時都為亂碼,以下分別為在servlet或action中獲取URL中的漢字解決辦法:

1.   以下程式碼為 通過HttpURLConnection連線來傳遞引數,其中,對待漢字的操作需要先進行編碼的操作,之後在服務端進行解碼操作即可。

	public static void main(String[] args) throws UnsupportedEncodingException {
		 
//		String url = "http://61.154.14.46:8080/exter.shtml?serviceType=1011";
		String name = java.net.URLEncoder.encode("行子愛上大叔的","UTF-8");
		String url = "http://localhost:8081/exter.shtml?serviceType=1023&guid=11&mobile=13696900475&content=123" + name;
//		String url = "http://localhost:8080/webtest/servlet/URLTest?name=這個是測試用的" + name;
//		String url = "http://localhost:8081/exter.shtml?serviceType=1022&menuId=4481&mobile=15806092760&text_data=linlinlin&imgName=testa.jpg";
//		getReturnData1(url);
		sendPost(url,null);
	} 

 /**
     * 通過HTTP協議以POST形式傳送指定檔案至指定url
     * @param url
     * @throws IOException
     */
    public static void sendPost(String url,InputStream in) {
        
    	HttpURLConnection conn = null;
    	OutputStreamWriter osw = null;
        try {
        	File file = new File("D:/test2.jpg");
			if(!file.exists()) {
				try {
					file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
            URL url1 = new URL(url);
            conn = (HttpURLConnection)url1.openConnection();
            conn.setReadTimeout(10000); // 快取的最長時間
            conn.setDoInput(true);// 允許輸入
            conn.setDoOutput(true);// 允許輸出
            conn.setUseCaches(false); // 不允許使用快取
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Charsert", "UTF-8"); 
            //conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + java.util.UUID.randomUUID().toString());
            //需要傳遞流時,一定要新增的引數,而且ACTION中通過request.getInputStream獲取流的情況下,也必須新增該引數
            conn.setRequestProperty("content-type", "text/html"); 
            OutputStream o = conn.getOutputStream();
    		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    		int BUFFER_SIZE = 1024; 
    		byte[] buf = new byte[BUFFER_SIZE];    
    		int size = 0;    
    	    try {
    			while ((size = bis.read(buf)) != -1)     
    			    o.write(buf, 0, size);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}    
    		finally {
    			try {
    				bis.close();
    				o.close();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		} 
            
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
                System.out.println( "connect failed!");
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally
        {
            if (osw != null)
                try {
                    osw.close() ;
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            
            if (conn != null)
                conn.disconnect() ;
        }
    }

2. servlet端的解析漢字操作:  直接進行編碼的轉換即可顯示為漢字
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

//		response.setContentType("text/html");
		request.setCharacterEncoding("UTF-8");
		String s = request.getParameter("name");
		System.out.println("s22 is " + new String(s.getBytes("iso-8859-1"),"UTF-8"));
		
//		InputStream in = request.getInputStream();
//		if(in != null) {
//			System.out.println("流不是空的。");
//			this.writeInputStreamToFile(in);
//			 System.out.println("server time is " + new Date());
//		} else {
//			System.out.println("流是空的。");
//		}

3. 在action中解析漢字的操作:   在action中直接設定下編碼格式,直接獲取就可。

    request.setCharacterEncoding("utf-8");

    System.out.println(form.getContent());