1 /* 2 * Copyright (C) 2014 Square, Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.squareup.okhttp; 17 18 import okio.Buffer; 19 20 /** 21 * Fluent API to build <a href="http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.1">HTML 22 * 2.0</a>-compliant form data. 23 */ 24 public final class FormEncodingBuilder { 25 private static final MediaType CONTENT_TYPE = 26 MediaType.parse("application/x-www-form-urlencoded"); 27 28 private final Buffer content = new Buffer(); 29 30 /** Add new key-value pair. */ 31 public FormEncodingBuilder add(String name, String value) { 32 if (content.size() > 0) { 33 content.writeByte('&'); 34 } 35 HttpUrl.canonicalize(content, name, 0, name.length(), 36 HttpUrl.FORM_ENCODE_SET, false, false, true, true); 37 content.writeByte('='); 38 HttpUrl.canonicalize(content, value, 0, value.length(), 39 HttpUrl.FORM_ENCODE_SET, false, false, true, true); 40 return this; 41 } 42 43 /** Add new key-value pair. */ 44 public FormEncodingBuilder addEncoded(String name, String value) { 45 if (content.size() > 0) { 46 content.writeByte('&'); 47 } 48 HttpUrl.canonicalize(content, name, 0, name.length(), 49 HttpUrl.FORM_ENCODE_SET, true, false, true, true); 50 content.writeByte('='); 51 HttpUrl.canonicalize(content, value, 0, value.length(), 52 HttpUrl.FORM_ENCODE_SET, true, false, true, true); 53 return this; 54 } 55 56 public RequestBody build() { 57 return RequestBody.create(CONTENT_TYPE, content.snapshot()); 58 } 59 } 60