Java URL Encode encodeForUrl(final String s)

Here you can find the source of encodeForUrl(final String s)

Description

encode For Url

License

Open Source License

Declaration

public static String encodeForUrl(final String s) 

Method Source Code

//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.io.UnsupportedEncodingException;

public class Main {
    public static String encodeForUrl(final String s) {
        final StringBuilder result = new StringBuilder();
        byte[] bytes;
        try {//from  w  w  w .j  a va 2  s .co m
            bytes = s.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Missing UTF-8 support?!", e);
        }
        for (byte aByte : bytes) {
            if (isUnreservedUrlCharacter((char) aByte)) {
                result.append((char) aByte);
            } else if (aByte == ' ') {
                result.append('+');
            } else {
                result.append(String.format("%%%02X", aByte));
            }
        }
        return result.toString();
    }

    private static boolean isUnreservedUrlCharacter(final char c) {
        return isLatinLetter(c) || isDigit(c) || c == '-' || c == '_' || c == '.' || c == '~';
    }

    private static boolean isLatinLetter(final char c) {
        return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z';
    }

    private static boolean isDigit(final char c) {
        return c >= '0' && c <= '9';
    }
}

Related

  1. encode(String value)
  2. encode(String value)
  3. encode(String value, String charset)
  4. encode(String value, String encoding)
  5. encodeArray(final String[] val)
  6. encodeSrcUrl(String fullUri)
  7. encodeStringURL(String str)
  8. encodeUri(String url)
  9. encodeURIComponent(String input)