servlet和action中获取URL中的汉字(解决URL中汉字为乱码的问题)

最近在项目中又遇到一个小问题,通过HttpURLConnection来传递汉字时,服务端获取汉字参数时都为乱码,以下分别为在servlet或action中获取URL中的汉字解决办法:

1. 以下代码为 通过HttpURLConnection连接来传递参数,其中,对待汉字的操作需要先进行编码的操作,之后在服务端进行解码操作即可。

  1. public static void main(String[] args) throws UnsupportedEncodingException {
  2. // String url = "http://61.154.14.46:8080/exter.shtml?serviceType=1011";
  3. String name = java.net.URLEncoder.encode("行子爱上大叔的","UTF-8");
  4. String url = "http://localhost:8081/exter.shtml?serviceType=1023&guid=11&mobile=13696900475&content=123" + name;
  5. // String url = "http://localhost:8080/webtest/servlet/URLTest?name=这个是测试用的" + name;
  6. // String url = "http://localhost:8081/exter.shtml?serviceType=1022&menuId=4481&mobile=15806092760&text_data=linlinlin&imgName=testa.jpg";
  7. // getReturnData1(url);
  8. sendPost(url,null);
  9. }
	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. HttpURLConnection conn = null;
  8. OutputStreamWriter osw = null;
  9. try {
  10. File file = new File("D:/test2.jpg");
  11. if(!file.exists()) {
  12. try {
  13. file.createNewFile();
  14. } catch (IOException e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. URL url1 = new URL(url);
  19. conn = (HttpURLConnection)url1.openConnection();
  20. conn.setReadTimeout(10000); // 缓存的最长时间
  21. conn.setDoInput(true);// 允许输入
  22. conn.setDoOutput(true);// 允许输出
  23. conn.setUseCaches(false); // 不允许使用缓存
  24. conn.setRequestMethod("POST");
  25. conn.setRequestProperty("Charsert", "UTF-8");
  26. //conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + java.util.UUID.randomUUID().toString());
  27. //需要传递流时,一定要添加的参数,而且ACTION中通过request.getInputStream获取流的情况下,也必须添加该参数
  28. conn.setRequestProperty("content-type", "text/html");
  29. OutputStream o = conn.getOutputStream();
  30. BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
  31. int BUFFER_SIZE = 1024;
  32. byte[] buf = new byte[BUFFER_SIZE];
  33. int size = 0;
  34. try {
  35. while ((size = bis.read(buf)) != -1)
  36. o.write(buf, 0, size);
  37. } catch (IOException e) {
  38. e.printStackTrace();
  39. }
  40. finally {
  41. try {
  42. bis.close();
  43. o.close();
  44. } catch (IOException e) {
  45. // TODO Auto-generated catch block
  46. e.printStackTrace();
  47. }
  48. }
  49. if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
  50. System.out.println( "connect failed!");
  51. } catch (IOException e) {
  52. e.printStackTrace();
  53. }
  54. finally
  55. {
  56. if (osw != null)
  57. try {
  58. osw.close() ;
  59. } catch (IOException e1) {
  60. e1.printStackTrace();
  61. }
  62. if (conn != null)
  63. conn.disconnect() ;
  64. }
  65. }
 /**
     * 通过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. // response.setContentType("text/html");
  4. request.setCharacterEncoding("UTF-8");
  5. String s = request.getParameter("name");
  6. System.out.println("s22 is " + new String(s.getBytes("iso-8859-1"),"UTF-8"));
  7. // InputStream in = request.getInputStream();
  8. // if(in != null) {
  9. // System.out.println("流不是空的。");
  10. // this.writeInputStreamToFile(in);
  11. // System.out.println("server time is " + new Date());
  12. // } else {
  13. // System.out.println("流是空的。");
  14. // }
	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());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值