---
title: "编码问题"
author: "yinter"
date: "2010-01-19T23:18:13Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-01-19T23:27:13Z"
id: 575168
url: "https://yinter.iteye.com/blog/575168"
---

在地址栏传输中文参数时，一般要对其进行编码转换，如URL里面包含特殊的字符和空格，使其能在传输后被对方解码识别；

中文的gbk(GB2312)编码
如果是中文的gbk(GB2312)编码，那么它的形式应该是这样的，即一个汉字对应两组%xx，即%xx%xx

中文的UTF-8编码
如果是中文的UTF-8编码，那么它的形式应该是这样的，即一个汉字对应三组%xx，即%xx%xx%xx

java.net.URLEncoder.encode()把中文转成UTF-8；
java.net.URLDecoder.decode()对其解码；

他不同于：

```java
private String changeCharset(String str, String oldCharset, String newCharset)
	   throws UnsupportedEncodingException {
	  if (str != null) {
	   //用旧的字符编码解码字符串。解码可能会出现异常。
	   byte[] bs = str.getBytes(oldCharset);
	   //用新的字符编码生成字符串
	   return new String(bs, newCharset);
	  }
	  return null;
	 }
	
private String changeCharset(String str, String newCharset) throws UnsupportedEncodingException {
		if (str != null) {
			// 用默认字符编码解码字符串。
			byte[] bs = str.getBytes();
			// 用新的字符编码生成字符串
			return new String(bs, newCharset);
		}
		return null;
	}

```