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

最近在項目中又遇到一個小問題,經過HttpURLConnection來傳遞漢字時,服務端獲取漢字參數時都爲亂碼,如下分別爲在servlet或action中獲取URL中的漢字解決辦法:html

1.   如下代碼爲 經過HttpURLConnection鏈接來傳遞參數,其中,對待漢字的操做須要先進行編碼的操做,以後在服務端進行解碼操做便可。java

  1.     public static void main(String[] args) throws UnsupportedEncodingException {  
  2.            
  3. //      String url = "http://61.154.14.46:8080/exter.shtml?serviceType=1011";   
  4.         String name = java.net.URLEncoder.encode("行子愛上大叔的","UTF-8");  
  5.         String url = "http://localhost:8081/exter.shtml?serviceType=1023&guid=11&mobile=13696900475&content=123" + name;  
  6. //      String url = "http://localhost:8080/webtest/servlet/URLTest?name=這個是測試用的" + name;   
  7. //      String url = "http://localhost:8081/exter.shtml?serviceType=1022&menuId=4481&mobile=15806092760&text_data=linlinlin&imgName=testa.jpg";   
  8. //      getReturnData1(url);   
  9.         sendPost(url,null);  
  10.     }   
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); }
  1. /** 
  2.     * 經過HTTP協議以POST形式發送指定文件至指定url 
  3.     * @param url 
  4.     * @throws IOException 
  5.     */  
  6.    public static void sendPost(String url,InputStream in) {  
  7.          
  8.     HttpURLConnection conn = null;  
  9.     OutputStreamWriter osw = null;  
  10.        try {  
  11.         File file = new File("D:/test2.jpg");  
  12.         if(!file.exists()) {  
  13.             try {  
  14.                 file.createNewFile();  
  15.             } catch (IOException e) {  
  16.                 e.printStackTrace();  
  17.             }  
  18.         }  
  19.            URL url1 = new URL(url);  
  20.            conn = (HttpURLConnection)url1.openConnection();  
  21.            conn.setReadTimeout(10000); // 緩存的最長時間   
  22.            conn.setDoInput(true);// 容許輸入   
  23.            conn.setDoOutput(true);// 容許輸出   
  24.            conn.setUseCaches(false); // 不容許使用緩存   
  25.            conn.setRequestMethod("POST");  
  26.            conn.setRequestProperty("Charsert""UTF-8");   
  27.            //conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + java.util.UUID.randomUUID().toString());   
  28.            //須要傳遞流時,必定要添加的參數,並且ACTION中經過request.getInputStream獲取流的狀況下,也必須添加該參數   
  29.            conn.setRequestProperty("content-type""text/html");   
  30.            OutputStream o = conn.getOutputStream();  
  31.         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));  
  32.         int BUFFER_SIZE = 1024;   
  33.         byte[] buf = new byte[BUFFER_SIZE];      
  34.         int size = 0;      
  35.         try {  
  36.             while ((size = bis.read(buf)) != -1)       
  37.                 o.write(buf, 0, size);  
  38.         } catch (IOException e) {  
  39.             e.printStackTrace();  
  40.         }      
  41.         finally {  
  42.             try {  
  43.                 bis.close();  
  44.                 o.close();  
  45.             } catch (IOException e) {  
  46.                 // TODO Auto-generated catch block   
  47.                 e.printStackTrace();  
  48.             }  
  49.         }   
  50.              
  51.            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)  
  52.                System.out.println( "connect failed!");  
  53.        } catch (IOException e) {  
  54.            e.printStackTrace();  
  55.        }  
  56.        finally  
  57.        {  
  58.            if (osw != null)  
  59.                try {  
  60.                    osw.close() ;  
  61.                } catch (IOException e1) {  
  62.                    e1.printStackTrace();  
  63.                }  
  64.              
  65.            if (conn != null)  
  66.                conn.disconnect() ;  
  67.        }  
  68.    }  
/** * 經過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端的解析漢字操做:  直接進行編碼的轉換便可顯示爲漢字

  1.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  2.             throws ServletException, IOException {  
  3.   
  4. //      response.setContentType("text/html");   
  5.         request.setCharacterEncoding("UTF-8");  
  6.         String s = request.getParameter("name");  
  7.         System.out.println("s22 is " + new String(s.getBytes("iso-8859-1"),"UTF-8"));  
  8.           
  9. //      InputStream in = request.getInputStream();   
  10. //      if(in != null) {   
  11. //          System.out.println("流不是空的。");   
  12. //          this.writeInputStreamToFile(in);   
  13. //           System.out.println("server time is " + new Date());   
  14. //      } else {   
  15. //          System.out.println("流是空的。");   
  16. //      }  
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");web

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

相關文章
相關標籤/搜索