Prepares the given HTTP body data.
514629
def prepare_body(self, data, files, json=None):
        """"""

        # Check if file, fo, generator, iterator.
        # If not, run through normal process.

        # Nottin' on you.
        body = None
        content_type = None

        if not data and json is not None:
            # urllib3 requires a bytes-like body. Python 2's json.dumps
            # provides this natively, but Python 3 gives a Unicode string.
            content_type = 'application/json'
            body = complexjson.dumps(json)
            if not isinstance(body, bytes):
                body = body.encode('utf-8')

        is_stream = all([
            hasattr(data, '__iter__'),
            not isinstance(data, (basestring, list, tuple, Mapping))
        ])

        try:
            length = super_len(data)
        except (TypeError, AttributeError, UnsupportedOperation):
            length = None

        if is_stream:
            body = data

            if getattr(body, 'tell', None) is not None:
                # Record the current file position before reading.
                # This will allow us to rewind a file in the event
                # of a redirect.
                try:
                    self._body_position = body.tell()
                except (IOError, OSError):
                    # This differentiates from None, allowing us to catch
                    # a failed `tell()` later when trying to rewind the body
                    self._body_position = object()

            if files:
                raise NotImplementedError('Streamed bodies and files are mutually exclusive.')

            if length:
                self.headers['Content-Length'] = builtin_str(length)
            else:
                self.headers['Transfer-Encoding'] = 'chunked'
        else:
            # Multi-part file uploads.
            if files:
                (body, content_type) = self._encode_files(files, data)
            else:
                if data:
                    body = self._encode_params(data)
                    if isinstance(data, basestring) or hasattr(data, 'read'):
                        content_type = None
                    else:
                        content_type = 'application/x-www-form-urlencoded'

            self.prepare_content_length(body)

            # Add content-type if it wasn't explicitly provided.
            if content_type and ('content-type' not in self.headers):
                self.headers['Content-Type'] = content_type

        self.body = body
544587
def _prepare_request(self, url, method, headers, data):
        

        request = httpclient.HTTPRequest(
            url=url, method=method, headers=headers, body=data,
            connect_timeout=self._connect_timeout,
            request_timeout=self._request_timeout,
            auth_username=self._username, auth_password=self._password,
            client_cert=self._client_cert, client_key=self._client_key,
            ca_certs=self._ca_certs, validate_cert=self._verify_cert)

        return request
920205
def prepare_url(method, params = {})
			timestamp = Time.now.utc.strftime('%Y%m%d%H%M%S')
			params[:method] = method
			params[:appid] = @appid
			params[:ts] = timestamp
			html_params = params.map { |k,v| "#{k.to_s}=#{v}" }.join("&")

			raw = @secret + params.keys.
					sort{ |a,b| a.to_s.downcase <=> b.to_s.downcase }.
					map{ |k| "#{k.to_s}#{params[k]}" }.
					join

			sig = Digest::MD5.hexdigest(raw)
			"http://cloud.scorm.com/api?#{html_params}&sig=#{sig}"
		end
804993
def http_method(self, data):
        """"""
        data = data.upper()
        if data in ['DELETE', 'GET', 'POST', 'PUT']:
            self._http_method = data

            # set content type for commit methods (best guess)
            if self._headers.get('Content-Type') is None and data in ['POST', 'PUT']:
                self.add_header('Content-Type', 'application/json')
        else:
            raise AttributeError(
                'Request Object Error: {} is not a valid HTTP method.'.format(data)
            )
606282
def __stringify_body(self, request_or_response):
        '''  '''
        headers = self.__track_info['{}_headers'.format(request_or_response)]
        body = self.__track_info.get('{}_body'.format(request_or_response))
    
        if isinstance(body, CaseInsensitiveDict):
            body = json.dumps(dict(body), ensure_ascii=False)
    
        elif isinstance(body, (dict, list)):
            body = json.dumps(body, indent=2, ensure_ascii=False)
    
        elif isinstance(body, bytes):
            resp_content_type = headers.get("Content-Type", "")
            try:
                if "image" in resp_content_type:
                    self.__track_info["response_data_type"] = "image"
                    body = "data:{};base64,{}".format(
                        resp_content_type,
                        b64encode(body).decode('utf-8')
                    )
                else:
                    body = escape(body.decode("utf-8"))
            except UnicodeDecodeError:
                pass
    
        elif not isinstance(body, (basestring, numeric_types, Iterable)):
            # class instance, e.g. MultipartEncoder()
            body = repr(body)
    
        self.__track_info['{}_body'.format(request_or_response)] = body
833210
def _prepare_body(self):
        
        content_type = self.__consume
        if not content_type:
            content_type = self.__op.consumes[0] if self.__op.consumes else 'application/json'
        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))

        # according to spec, payload should be one and only,
        # so we just return the first value in dict.
        for parameter in self.__op.parameters:
            parameter = final(parameter)
            if getattr(parameter, 'in') == 'body':
                schema = deref(parameter.schema)
                _type = schema.type
                _format = schema.format
                name = schema.name
                body = self.__p['body'][parameter.name]
                return content_type, self.__op._mime_codec.marshal(content_type, body, _type=_type, _format=_format, name=name)
        return None, None
508654
private HttpURLConnection prepareConnection(Map<String, String> extraHeaders) throws IOException {
		
		// create URLConnection
		HttpURLConnection connection = (HttpURLConnection) serviceUrl.openConnection(connectionProxy);
		connection.setConnectTimeout(connectionTimeoutMillis);
		connection.setReadTimeout(readTimeoutMillis);
		connection.setAllowUserInteraction(false);
		connection.setDefaultUseCaches(false);
		connection.setDoInput(true);
		connection.setDoOutput(true);
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(true);
		connection.setRequestMethod("POST");
		
		setupSsl(connection);
		addHeaders(extraHeaders, connection);
		
		return connection;
	}
1162926
private HttpPost preparePost(final String url) {
    final HttpPost httpPost = new HttpPost(this.instanceUrl + url);
    for (final Header header : this.headers) {
      httpPost.addHeader(header);
    }
    return httpPost;
  }
65690
def prepare(self):
        '''
        
        '''
        # Find an acceptable content-type
        accept_header = self.request.headers.get('Accept', '*/*')
        # Ignore any parameter, including q (quality) one
        parsed_accept_header = [cgi.parse_header(h)[0] for h in accept_header.split(',')]

        def find_acceptable_content_type(parsed_accept_header):
            for media_range in parsed_accept_header:
                for content_type, dumper in self.ct_out_map:
                    if fnmatch.fnmatch(content_type, media_range):
                        return content_type, dumper
            return None, None

        content_type, dumper = find_acceptable_content_type(parsed_accept_header)

        # better return message?
        if not content_type:
            self.send_error(406)

        self.content_type = content_type
        self.dumper = dumper

        # do the common parts
        self.start = time.time()
        self.connected = True

        self.lowstate = self._get_lowstate()
20168
def prepare_params(request):
    """"""
    return request.replace(
        params={key: dump_param(val) for key, val in request.params.items()
                if val is not None})
238622
protected function prepare()
    {
        if (!is_array($this->data) || count($this->data) == 0) {
            $this->setData($this->read());
        }
    }
332361
def _http(method, url, headers=None, **kw):
    '''
    
    '''
    params = None
    boundary = None
    if method == 'UPLOAD':
        params, boundary = _encode_multipart(**kw)
    else:
        params = _encode_params(**kw)
    http_url = '%s?%s' % (url, params) if method == _HTTP_GET else url
    http_body = None if method == 'GET' else params
    logging.error('%s: %s' % (method, http_url))
    req = urllib2.Request(http_url, data=http_body)
    req.add_header('Accept-Encoding', 'gzip')
    if headers:
        for k, v in headers.iteritems():
            req.add_header(k, v)
    if boundary:
        req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
    try:
        resp = urllib2.urlopen(req, timeout=5)
        return _read_http_body(resp)
    finally:
        pass
1290253
def init_body_buffer(self, method, headers):
        
        content_length = headers.get("CONTENT-LENGTH", None)

        if method in (HTTPMethod.POST, HTTPMethod.PUT):
            if content_length is None:
                raise HTTPErrorBadRequest("HTTP Method requires a CONTENT-LENGTH header")
            self.content_length = int(content_length)
            self.body_buffer = bytearray(0)

        elif content_length is not None:
            raise HTTPErrorBadRequest(
                "HTTP method %s may NOT have a CONTENT-LENGTH header"
            )
188774
def prepare(self, data):
        
        def expand(data):
            for name, value in data.items():
                if isinstance(value, Iterable):
                    for value in value:
                        yield name, value
                else:
                    yield name, value

        # `data` must be an iterable yielding 2-tuples.
        if self.action.method in ("GET", "DELETE"):
            # MAAS does not expect an entity-body for GET or DELETE.
            data = expand(data)
        else:
            # MAAS expects and entity-body for PUT and POST.
            data = data.items()

        # Bundle things up ready to throw over the wire.
        uri, body, headers = utils.prepare_payload(
            self.action.op, self.action.method, self.uri, data)

        # Headers are returned as a list, but they must be a dict for
        # the signing machinery.
        headers = dict(headers)

        # Sign request if credentials have been provided.
        credentials = self.action.handler.session.credentials
        if credentials is not None:
            utils.sign(uri, headers, credentials)

        return uri, body, headers
13314
private void prepareRequestBody() throws IOException {

    if (bodyByteArray != null) {
      setByteArrayBody();
    } else if (bodyString != null) {
      setStringBody();
    } else if (bodyObject != null) {
      setTypedBody();
    }
  }
13770
protected void prepareForwardedResponseHeaders(ResponseData response) {
        HttpHeaders headers = response.getHeaders();
        headers.remove(TRANSFER_ENCODING);
        headers.remove(CONNECTION);
        headers.remove("Public-Key-Pins");
        headers.remove(SERVER);
        headers.remove("Strict-Transport-Security");
    }
743763
def prepare(self):
        
        # Maybe the Brok is a old daemon one or was already prepared
        # if so, the data is already ok
        if hasattr(self, 'prepared') and not self.prepared:
            self.data = unserialize(self.data)
            if self.instance_id:
                self.data['instance_id'] = self.instance_id
        self.prepared = True