HttpURLConnection的URL包含中文字符时乱码的解决办法

URL中包含的汉字个数及位置不确定,只能一个一个字符去找出来进行编码。

代码如下:

 

	private static String getUtf8Url(String url) {
		char[] chars = url.toCharArray();
		StringBuilder utf8Url = new StringBuilder();
		final int charCount = chars.length;
		for (int i = 0; i < charCount; i++) {
			byte[] bytes = ("" + chars[i]).getBytes();
			if (bytes.length == 1) {
				utf8Url.append(chars[i]);
			}else{
				try {
					utf8Url.append(URLEncoder.encode(String.valueOf(chars[i]), "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return utf8Url.toString();
	}

你可能感兴趣的:(HttpURLConnection的URL包含中文字符时乱码的解决办法)