View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.client.util;
20  
21  import java.io.UnsupportedEncodingException;
22  import java.net.URLEncoder;
23  import java.nio.charset.Charset;
24  import java.nio.charset.StandardCharsets;
25  import java.nio.charset.UnsupportedCharsetException;
26  
27  import org.eclipse.jetty.util.Fields;
28  
29  /**
30   * A {@link ContentProvider} for form uploads with the
31   * "application/x-www-form-urlencoded" content type.
32   */
33  public class FormContentProvider extends StringContentProvider
34  {
35      public FormContentProvider(Fields fields)
36      {
37          this(fields, StandardCharsets.UTF_8);
38      }
39  
40      public FormContentProvider(Fields fields, Charset charset)
41      {
42          super("application/x-www-form-urlencoded", convert(fields, charset), charset);
43      }
44  
45      public static String convert(Fields fields)
46      {
47          return convert(fields, StandardCharsets.UTF_8);
48      }
49  
50      public static String convert(Fields fields, Charset charset)
51      {
52          // Assume 32 chars between name and value.
53          StringBuilder builder = new StringBuilder(fields.getSize() * 32);
54          for (Fields.Field field : fields)
55          {
56              for (String value : field.getValues())
57              {
58                  if (builder.length() > 0)
59                      builder.append("&");
60                  builder.append(encode(field.getName(), charset)).append("=").append(encode(value, charset));
61              }
62          }
63          return builder.toString();
64      }
65  
66      private static String encode(String value, Charset charset)
67      {
68          try
69          {
70              return URLEncoder.encode(value, charset.name());
71          }
72          catch (UnsupportedEncodingException x)
73          {
74              throw new UnsupportedCharsetException(charset.name());
75          }
76      }
77  }