View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2016 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.client.api.ContentProvider;
28  import org.eclipse.jetty.util.Fields;
29  
30  /**
31   * A {@link ContentProvider} for form uploads with the
32   * "application/x-www-form-urlencoded" content type.
33   */
34  public class FormContentProvider extends StringContentProvider
35  {
36      public FormContentProvider(Fields fields)
37      {
38          this(fields, StandardCharsets.UTF_8);
39      }
40  
41      public FormContentProvider(Fields fields, Charset charset)
42      {
43          super("application/x-www-form-urlencoded", convert(fields, charset), charset);
44      }
45  
46      public static String convert(Fields fields)
47      {
48          return convert(fields, StandardCharsets.UTF_8);
49      }
50  
51      public static String convert(Fields fields, Charset charset)
52      {
53          // Assume 32 chars between name and value.
54          StringBuilder builder = new StringBuilder(fields.getSize() * 32);
55          for (Fields.Field field : fields)
56          {
57              for (String value : field.getValues())
58              {
59                  if (builder.length() > 0)
60                      builder.append("&");
61                  builder.append(encode(field.getName(), charset)).append("=").append(encode(value, charset));
62              }
63          }
64          return builder.toString();
65      }
66  
67      private static String encode(String value, Charset charset)
68      {
69          try
70          {
71              return URLEncoder.encode(value, charset.name());
72          }
73          catch (UnsupportedEncodingException x)
74          {
75              throw new UnsupportedCharsetException(charset.name());
76          }
77      }
78  }