content-type: multipart/json
972280
private Map<String, Object> getMultipartBodyAsDictionary() throws CouchbaseLiteException {
        MultipartDocumentReader reader = new MultipartDocumentReader(db);
        reader.setHeaders(Utils.headersToMap(connection.getRequestProperties()));
        byte[] buffer = new byte[BUF_LEN];
        int numBytesRead;
        InputStream contentStream = connection.getRequestInputStream();
        try {
            while ((numBytesRead = contentStream.read(buffer)) != -1)
                reader.appendData(buffer, 0, numBytesRead);
        } catch (IOException ioe) {
            Log.e(Log.TAG_ROUTER, "Error in load data from stream.");
            throw new CouchbaseLiteException(Status.BAD_REQUEST);
        } finally {
            if (contentStream != null) {
                try {
                    contentStream.close();
                } catch (IOException ioe) {
                }
            }
        }
        reader.finish();
        return reader.getDocumentProperties();
    }
1299491
def outputjson(self, obj):
        
        self.header('Content-Type', 'application/json')
        self.outputdata(json.dumps(obj).encode('ascii'))
881488
def _json_pretty_print(self, content):
        
        temp = json.loads(content)
        return json.dumps(
            temp,
            sort_keys=True,
            indent=4,
            separators=(
                ',',
                ': '))
1216062
async def parse(self, request):
        
        if request.content_type in {'application/x-www-form-urlencoded', 'multipart/form-data'}:
            return await request.post()

        if request.content_type == 'application/json':
            return await request.json()

        return await request.text()
919921
def parse_multipart_form(body, boundary):
    
    files = RequestParameters()
    fields = RequestParameters()

    form_parts = body.split(boundary)
    for form_part in form_parts[1:-1]:
        file_name = None
        content_type = "text/plain"
        content_charset = "utf-8"
        field_name = None
        line_index = 2
        line_end_index = 0
        while not line_end_index == -1:
            line_end_index = form_part.find(b"\r\n", line_index)
            form_line = form_part[line_index:line_end_index].decode("utf-8")
            line_index = line_end_index + 2

            if not form_line:
                break

            colon_index = form_line.index(":")
            form_header_field = form_line[0:colon_index].lower()
            form_header_value, form_parameters = parse_header(
                form_line[colon_index + 2 :]
            )

            if form_header_field == "content-disposition":
                field_name = form_parameters.get("name")
                file_name = form_parameters.get("filename")

                # non-ASCII filenames in RFC2231, "filename*" format
                if file_name is None and form_parameters.get("filename*"):
                    encoding, _, value = email.utils.decode_rfc2231(
                        form_parameters["filename*"]
                    )
                    file_name = unquote(value, encoding=encoding)
            elif form_header_field == "content-type":
                content_type = form_header_value
                content_charset = form_parameters.get("charset", "utf-8")

        if field_name:
            post_data = form_part[line_index:-4]
            if file_name is None:
                value = post_data.decode(content_charset)
                if field_name in fields:
                    fields[field_name].append(value)
                else:
                    fields[field_name] = [value]
            else:
                form_file = File(
                    type=content_type, name=file_name, body=post_data
                )
                if field_name in files:
                    files[field_name].append(form_file)
                else:
                    files[field_name] = [form_file]
        else:
            logger.debug(
                "Form-data field does not have a 'name' parameter "
                "in the Content-Disposition header"
            )

    return fields, files
957741
def json_request(request_class, path, data = {}, header = {})
      Itrp::Attachments.new(self).upload_attachments!(path, data)
      request = request_class.new(expand_path(path), expand_header(header))
      body = {}
      data.each{ |k,v| body[k.to_s] = typecast(v, false) }
      request.body = body.to_json
      request
    end
326017
function downloadMultipart (headers, opts, handle) {
  if (!handle) {
    handle = opts
    opts = {}
  }

  assert.equal(typeof headers, 'object', 'multipart-stream: headers should be an object')
  assert.equal(typeof opts, 'object', 'multipart-stream: opts should be an object')
  assert.equal(typeof handle, 'function', 'multipart-stream: handle should be a function')

  opts = xtend(content.type(headers['content-type']), opts)
  var dispenser = new pez.Dispenser(opts)

  dispenser.on('part', function (part) {
    var encoding = part.headers['content-transfer-encoding']
    encoding = (encoding) ? encoding.toLowerCase() : '7bit'

    handle(part.name, part, part.filename, encoding, part.headers['content-type'])
  })

  return dispenser
}
1102349
function parseHttpBody(req, cb) {
	// check for multipart streams that can contain file uploads

	var contentType = req.headers['content-type'];
	var m = contentType && contentType.match(/^multipart\/form-data; boundary=(.+)$/);

	if (m && m[1]) {
		parseMultipart(req, m[1], cb);
	} else {
		parseSinglepart(req, cb);
	}
}
263725
function(obj) {
    //todo: support file type (useful?)
    var result = {};
    result.boundry = '-------------------------------'+Math.floor(Math.random()*1000000000);
    var lines = [];
    for(var p in obj){
        if (obj.hasOwnProperty(p)) {
            lines.push(
                '--'+result.boundry+"\n"+
                'Content-Disposition: form-data; name="'+p+'"'+"\n"+
                "\n"+
                obj[p]+"\n"
            );
        }
    }
    lines.push( '--'+result.boundry+'--' );
    result.body = lines.join('');
    result.length = result.body.length;
    result.type = 'multipart/form-data; boundary='+result.boundry;
    return result;
  }
859357
def formdata_encode(fields):
    
    BOUNDARY = '----form-data-boundary-ZmRkNzJkMjUtMjkyMC00'
    out = []
    for (key, value) in fields.items():
        out.append('--' + BOUNDARY)
        out.append('Content-Disposition: form-data; name="%s"' % key)
        out.append('')
        out.append(value)
    out.append('--' + BOUNDARY + '--')
    out.append('')
    body = '\r\n'.join(out)
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
    return content_type, body
1358601
def is_multipart(header_dict):
    
    return (
        {k.lower(): v for k, v in header_dict.items()}
        .get('content-type', '')
        .startswith('multipart')
    )
845570
def json(self):
        
        try:
            return json.loads(self.text)
        except Exception as e:
            raise ContentDecodingError(e)
585829
function parseJSON( path, content ) {

            return JSON.parse( content, function( key, value ) {

                if ( options.stripComments && key === "{{comment}}" ) return undefined;

                // Replace variables in their values

                if ( Object.keys( options.variables ).length && typeof value === "string" ) {
                    value = replaceVariables( value );
                }

                var match = ( typeof value === "string" ) ? value.match( options.parsePattern ) : null;

                if ( match ) {
                    var folderPath = getFolder( path ) || ".";
                    var fullPath = folderPath + "/" + match[ 1 ];

                    return isDirectory( fullPath ) ? parseDirectory( fullPath ) : parseFile( fullPath );
                }

                return value;

            } );
        }
593236
def _prepare_files(self, encoding):
        
        content_type = 'multipart/form-data'
        if self.__op.consumes and content_type not in self.__op.consumes:
            raise errs.SchemaError('content type {0} does not present in {1}'.format(content_type, self.__op.consumes))

        boundary = uuid4().hex
        content_type += '; boundary={0}'
        content_type = content_type.format(boundary)

        # init stream
        body = io.BytesIO()
        w = codecs.getwriter(encoding)

        def append(name, obj):
            body.write(six.b('--{0}\r\n'.format(boundary)))

            # header
            w(body).write('Content-Disposition: form-data; name="{0}"; filename="{1}"'.format(name, obj.filename))
            body.write(six.b('\r\n'))
            if 'Content-Type' in obj.header:
                w(body).write('Content-Type: {0}'.format(obj.header['Content-Type']))
                body.write(six.b('\r\n'))
            if 'Content-Transfer-Encoding' in obj.header:
                w(body).write('Content-Transfer-Encoding: {0}'.format(obj.header['Content-Transfer-Encoding']))
                body.write(six.b('\r\n'))
            body.write(six.b('\r\n'))

            # body
            if not obj.data:
                with open(obj.filename, 'rb') as f:
                    body.write(f.read())
            else:
                data = obj.data.read()
                if isinstance(data, six.text_type):
                    w(body).write(data)
                else:
                    body.write(data)

            body.write(six.b('\r\n'))

        for k, v in self.__p['formData']:
            body.write(six.b('--{0}\r\n'.format(boundary)))

            w(body).write('Content-Disposition: form-data; name="{0}"'.format(k))
            body.write(six.b('\r\n'))
            body.write(six.b('\r\n'))

            w(body).write(v)

            body.write(six.b('\r\n'))

        # begin of file section
        for k, v in six.iteritems(self.__p['file']):
            if isinstance(v, list):
                for vv in v:
                    append(k, vv)
            else:
                append(k, v)

        # final boundary
        body.write(six.b('--{0}--\r\n'.format(boundary)))

        return content_type, body.getvalue()
65582
def json(self):
        '''  '''
        if 'application/json' in self.environ.get('CONTENT_TYPE', '') \
        and 0 < self.content_length < self.MEMFILE_MAX:
            return json_loads(self.body.read(self.MEMFILE_MAX))
        return None
1373377
private void setMultipart(String contentType) {
        String[] dataBoundary = HttpPostRequestDecoder.getMultipartDataBoundary(contentType);
        if (dataBoundary != null) {
            multipartDataBoundary = dataBoundary[0];
            if (dataBoundary.length > 1 && dataBoundary[1] != null) {
                charset = Charset.forName(dataBoundary[1]);
            }
        } else {
            multipartDataBoundary = null;
        }
        currentStatus = MultiPartStatus.HEADERDELIMITER;
    }
641009
def content(self, request, id):
        
        gist = self.send(request, id).json()

        def convert(data):
            return base64.b64decode(data).decode('utf-8')

        content = {}
        for name, data in gist['files'].items():
            content[name] = convert(data['content'])

        return content