Java URL Encode encode(String strInput)

Here you can find the source of encode(String strInput)

Description

Encode URL string by method URLEncoder.encode() - after this encoding all spaces will be encoded as + character.

License

Open Source License

Parameter

Parameter Description
strInput - input string that has to be encoded

Exception

Parameter Description
UnsupportedEncodingException - error while encode process

Return

- encoded string

Declaration

public static String encode(String strInput) throws UnsupportedEncodingException 

Method Source Code

//package com.java2s;
/*//from ww w  .j  av  a 2s  .co m
 * Copyright (C) 2003 - 2014 OpenSubsystems.com/net/org and its owners. All rights reserved.
 * 
 * This file is part of OpenSubsystems.
 *
 * OpenSubsystems is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class Main {
    /**
     * Encode URL string by method URLEncoder.encode() - after this encoding 
     * all spaces will be encoded as + character. But there is also problem 
     * with decoding this + character - it is decoded again as character + . 
     * It means after 1st encode process we will replace all occurrences of + by 
     * code for space.
     * E.g.  input string  = "abc def"
     *       after encoded = "abc+def"
     *       after replace = "abc%20def"
     * @param strInput - input string that has to be encoded
     * @return - encoded string
     * @throws UnsupportedEncodingException - error while encode process
     */
    public static String encode(String strInput) throws UnsupportedEncodingException {
        String strEncoded = URLEncoder.encode(strInput, "UTF-8");
        return strEncoded.replaceAll("\\+", "%20");
    }
}

Related

  1. encode(String source)
  2. encode(String src, String srcCode, String destCode)
  3. encode(String str)
  4. encode(String str)
  5. encode(String string)
  6. encode(String text)
  7. encode(String toBeEncoded, String charSet, String defaultReturnValue)
  8. encode(String value)
  9. encode(String value)