HTTP URL Address Encoding in Java

前端 未结 26 1361
醉酒成梦
醉酒成梦 2020-11-22 01:35

My Java standalone application gets a URL (which points to a file) from the user and I need to hit it and download it. The problem I am facing is that I am not able to encod

26条回答
  •  盖世英雄少女心
    2020-11-22 02:29

    Unfortunately, org.apache.commons.httpclient.util.URIUtil is deprecated, and the replacement org.apache.commons.codec.net.URLCodec does coding suitable for form posts, not in actual URL's. So I had to write my own function, which does a single component (not suitable for entire query strings that have ?'s and &'s)

    public static String encodeURLComponent(final String s)
    {
      if (s == null)
      {
        return "";
      }
    
      final StringBuilder sb = new StringBuilder();
    
      try
      {
        for (int i = 0; i < s.length(); i++)
        {
          final char c = s.charAt(i);
    
          if (((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')) ||
              ((c >= '0') && (c <= '9')) ||
              (c == '-') ||  (c == '.')  || (c == '_') || (c == '~'))
          {
            sb.append(c);
          }
          else
          {
            final byte[] bytes = ("" + c).getBytes("UTF-8");
    
            for (byte b : bytes)
            {
              sb.append('%');
    
              int upper = (((int) b) >> 4) & 0xf;
              sb.append(Integer.toHexString(upper).toUpperCase(Locale.US));
    
              int lower = ((int) b) & 0xf;
              sb.append(Integer.toHexString(lower).toUpperCase(Locale.US));
            }
          }
        }
    
        return sb.toString();
      }
      catch (UnsupportedEncodingException uee)
      {
        throw new RuntimeException("UTF-8 unsupported!?", uee);
      }
    }
    

提交回复
热议问题