Prepares the request body - setting the body, charset and
content length by body type

@throws IOException
13314
private void prepareRequestBody() throws IOException {

    if (bodyByteArray != null) {
      setByteArrayBody();
    } else if (bodyString != null) {
      setStringBody();
    } else if (bodyObject != null) {
      setTypedBody();
    }
  }
305547
def __SetBody(self, http_request, method_config, request, upload):
        """"""
        if not method_config.request_field:
            return

        request_type = _LoadClass(
            method_config.request_type_name, self.__client.MESSAGES_MODULE)
        if method_config.request_field == REQUEST_IS_BODY:
            body_value = request
            body_type = request_type
        else:
            body_value = getattr(request, method_config.request_field)
            body_field = request_type.field_by_name(
                method_config.request_field)
            util.Typecheck(body_field, messages.MessageField)
            body_type = body_field.type

        # If there was no body provided, we use an empty message of the
        # appropriate type.
        body_value = body_value or body_type()
        if upload and not body_value:
            # We're going to fill in the body later.
            return
        util.Typecheck(body_value, body_type)
        http_request.headers['content-type'] = 'application/json'
        http_request.body = self.__client.SerializeMessage(body_value)
858681
private void sendResponse(HttpServletResponse servletResponse, RESTResponse restResponse) throws IOException {
        servletResponse.setStatus(restResponse.getCode().getCode());
        
        Map<String, String> responseHeaders = restResponse.getHeaders();
        if (responseHeaders != null) {
            for (Map.Entry<String, String> mapEntry : responseHeaders.entrySet()) {
                if (mapEntry.getKey().equalsIgnoreCase(HttpDefs.CONTENT_TYPE)) {
                    servletResponse.setContentType(mapEntry.getValue());
                } else {
                    servletResponse.setHeader(mapEntry.getKey(), mapEntry.getValue());
                }
            }
        }
        
        byte[] bodyBytes = restResponse.getBodyBytes();
        int bodyLen = bodyBytes == null ? 0 : bodyBytes.length;
        servletResponse.setContentLength(bodyLen);
        
        if (bodyLen > 0 && servletResponse.getContentType() == null) {
            servletResponse.setContentType("text/plain");
        }
        
        if (bodyLen > 0) {
            servletResponse.getOutputStream().write(restResponse.getBodyBytes());
        }
    }
309389
private String getRequestBody(ServletRequest request) throws IOException {

        final StringBuilder sb = new StringBuilder();

        String line = request.getReader().readLine();
        while (null != line) {
            sb.append(line);
            line = request.getReader().readLine();
        }

        return sb.toString();
    }
1088932
def prepare_request(self, method, url, body=''):
        
        headers = {
            'Content-type': 'application/json',
        }
        # Note: we don't pass body to sign() since it's only for bodies that
        # are form-urlencoded. Similarly, we don't care about the body that
        # sign() returns.
        uri, signed_headers, signed_body = self.oauth_client.sign(
            url, http_method=method, headers=headers)
        if body:
            if method == 'GET':
                body = urllib.urlencode(body)
            else:
                body = json.dumps(body)
        headers.update(signed_headers)
        return {"headers": headers, "data": body}
1009438
public PactDslRequestWithPath body(Supplier<String> body, String mimeType) {
        requestBody = OptionalBody.body(body.get().getBytes());
        requestHeaders.put(CONTENT_TYPE, Collections.singletonList(mimeType));
        return this;
    }
974797
void parseNextResponse() throws IOException {
    contentId++;

    // Extract the outer headers.
    String line;
    while ((line = readLine()) != null && !line.equals("")) {
      // Do nothing.
    }

    // Extract the status code.
    String statusLine = readLine();
    String[] statusParts = statusLine.split(" ");
    int statusCode = Integer.parseInt(statusParts[1]);

    // Extract and store the inner headers.
    // TODO(rmistry): Handle inner headers that span multiple lines. More details here:
    // http://tools.ietf.org/html/rfc2616#section-2.2
    List<String> headerNames = new ArrayList<String>();
    List<String> headerValues = new ArrayList<String>();
    long contentLength = -1L;
    while ((line = readLine()) != null && !line.equals("")) {
      String[] headerParts = line.split(": ", 2);
      String headerName = headerParts[0];
      String headerValue = headerParts[1];
      headerNames.add(headerName);
      headerValues.add(headerValue);
      if ("Content-Length".equalsIgnoreCase(headerName.trim())) {
          contentLength = Long.parseLong(headerValue);
      }
    }

    InputStream body;
    if (contentLength == -1) {
      // This isn't very efficient, but most respectable servers should set the Content-Length
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      while ((line = readRawLine()) != null && !line.startsWith(boundary)) {
        // Convert characters back to bytes:
        buffer.write(line.getBytes("ISO-8859-1"));
      }

      // Remove CRLF that separates body from boundary token
      body = trimCrlf(buffer.toByteArray());

      // Remove CRLF from the boundary token (to match readLine)
      line = trimCrlf(line);
    } else {
      body = new FilterInputStream(ByteStreams.limit(inputStream, contentLength)) {
        @Override
        public void close() {
          // Don't allow the parser to close the underlying stream
        }
      };
    }

    HttpResponse response =
        getFakeResponse(statusCode, body, headerNames, headerValues);

    parseAndCallback(requestInfos.get(contentId - 1), statusCode, response);

    // Consume any bytes that were not consumed by the parser
    while (body.skip(contentLength) > 0 || body.read() != -1) {
    }

    if (contentLength != -1) {
      line = readLine();
    } else {
      // The line was already read
    }
    // Consume any blank lines that follow the response (not included in Content-Length)
    while ((line != null) && (line.length() == 0)) {
      line = readLine();
    }

    checkForFinalBoundary(line);
  }
1148173
def setup_streaming(request)
      if(request.body && request.body.respond_to?(:read))
        body = request.body
        request.content_length = body.respond_to?(:lstat) ? body.lstat.size : body.size
        request.body_stream = request.body
        true
      end
    end
448248
protected function prepareRequest()
    {
        $this->formatUrl();
        $this->validateInput();
        $this->addHeaders();
        $this->addRequestBody();
        $this->initOptions();
    }
1250395
@SuppressWarnings(
        {
            "PMD.InsufficientStringBufferDeclaration",
            "PMD.AvoidInstantiatingObjectsInLoops"
        })
    private static StringBuilder fakeBody(final Request... parts)
        throws IOException {
        final StringBuilder builder = new StringBuilder();
        for (final Request part : parts) {
            builder.append(String.format("--%s", RqMtFake.BOUNDARY))
                .append(RqMtFake.CRLF)
                .append("Content-Disposition: ")
                .append(
                    new RqHeaders.Smart(
                        new RqHeaders.Base(part)
                    ).single("Content-Disposition")
                ).append(RqMtFake.CRLF);
            final String body = new RqPrint(part).printBody();
            if (!(RqMtFake.CRLF.equals(body) || body.isEmpty())) {
                builder.append(RqMtFake.CRLF)
                    .append(body)
                    .append(RqMtFake.CRLF);
            }
        }
        builder.append("Content-Transfer-Encoding: utf-8")
            .append(RqMtFake.CRLF)
            .append(String.format("--%s--", RqMtFake.BOUNDARY));
        return builder;
    }
818278
def set_data(self, value):
        
        # if an unicode string is set, it's encoded directly so that we
        # can set the content length
        if isinstance(value, text_type):
            value = value.encode(self.charset)
        else:
            value = bytes(value)
        self.response = [value]
        if self.automatically_set_content_length:
            self.headers['Content-Length'] = str(len(value))
1077007
private <T> HttpUriRequest prepareRequest(URI uri, Map<String, String> headers, String jsonData) {
        HttpUriRequest httpRequest;
        if (jsonData != null) {
            // POST data
            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(new StringEntity(jsonData, ContentType.APPLICATION_JSON));
            httpRequest = httpPost;
        } else {
            // GET request
            httpRequest = new HttpGet(uri);
        }
        httpRequest.addHeader(HttpHeaders.ACCEPT, "application/json");
        headers.forEach(httpRequest::addHeader);

        return httpRequest;
    }
34038
public String body() throws HttpException {
		try {
			return HttpUtil.getString(bodyBytes(), this.charset, null == this.charsetFromResponse);
		} catch (IOException e) {
			throw new HttpException(e);
		}
	}
904029
protected void setContentType (HttpServletRequest request, HttpServletResponse response)
    {
        String contentType = _defaultContentType;
        int index = contentType.lastIndexOf(';') + 1;
        if (index <= 0 || (index < contentType.length() &&
                           contentType.indexOf("charset", index) == -1)) {
            // append the character encoding which we'd like to use
            String encoding = chooseCharacterEncoding(request);
            if (!DEFAULT_OUTPUT_ENCODING.equalsIgnoreCase(encoding)) {
                contentType += "; charset=" + encoding;
            }
        }
        response.setContentType(contentType);
    }
1207837
public void setData(final InputStream in) throws IOException {
		final byte[] bytes = JKIOUtil.readStream(in);
		setData(bytes);
	}
543037
def prepare_body(self, data, files):
        """"""

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

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

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

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

        if is_stream:
            body = data

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

            if length is not None:
                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 (not 'content-type' in self.headers):
                self.headers['Content-Type'] = content_type

        self.body = body
1297568
public void setBody(byte[] contents) {
		if (contents == null) {
			return;
		}
		cachedString = null;
		
		body = new byte[contents.length];
		System.arraycopy(contents, 0, body, 0, contents.length);
		
		pos = body.length;
	}