Java tutorial
//package com.java2s; /* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.StringTokenizer; public class Main { public static String encodeUrl(String url, String charset) throws UnsupportedEncodingException { if (url == null) { return ""; } int index = url.indexOf("?"); if (index >= 0) { String result = url.substring(0, index + 1); String paramsPart = url.substring(index + 1); StringTokenizer tokenizer = new StringTokenizer(paramsPart, "&"); while (tokenizer.hasMoreTokens()) { String definition = tokenizer.nextToken(); int eqIndex = definition.indexOf("="); if (eqIndex >= 0) { String paramName = definition.substring(0, eqIndex); String paramValue = definition.substring(eqIndex + 1); result += paramName + "=" + encodeUrlParam(paramValue, charset) + "&"; } else { result += encodeUrlParam(definition, charset) + "&"; } } if (result.endsWith("&")) { result = result.substring(0, result.length() - 1); } return result; } return url; } private static String encodeUrlParam(String value, String charset) throws UnsupportedEncodingException { if (value == null) { return ""; } try { String decoded = URLDecoder.decode(value, charset); String result = ""; for (int i = 0; i < decoded.length(); i++) { char ch = decoded.charAt(i); result += (ch == '#') ? "#" : URLEncoder.encode(String.valueOf(ch), charset); } return result; } catch (IllegalArgumentException e) { return value; } } }