Return a string containing a nicely formatted representation of the request
        and response objects for logging and debugging.

        - Note: Does not work if the request or response body is a MultipartEncoder
          object.
495886
def dump_request_and_response(self, response):
        
        if response.reason is None:
            response.reason = "<unknown>"
        return d1_client.util.normalize_request_response_dump(
            requests_toolbelt.utils.dump.dump_response(response)
        )
690786
def get_request_body(self):
        
        if self._request_body is None:
            content_type_str = self.request.headers.get(
                'Content-Type', 'application/octet-stream')
            LOGGER.debug('decoding request body of type %s', content_type_str)
            content_type = headers.parse_content_type(content_type_str)
            try:
                selected, requested = algorithms.select_content_type(
                    [content_type], _content_types.values())
            except errors.NoMatch:
                raise web.HTTPError(
                    415, 'cannot decoded content type %s', content_type_str,
                    reason='Unexpected content type')
            handler = _content_handlers[str(selected)]
            try:
                self._request_body = handler.unpack_bytes(
                    self.request.body,
                    encoding=content_type.parameters.get('charset'),
                )
            except ValueError as error:
                raise web.HTTPError(
                    400, 'failed to decode content body - %r', error,
                    reason='Content body decode failure')
        return self._request_body
469607
private String getErrorHttpResponseMsg(HttpRequest httpRequest, StatusLine responseStatus) {
		StringBuilder sb = new StringBuilder("HttpRequest:").append(httpRequest.toString());
		sb.append("\nHttpResponse:");
		if (responseStatus.getProtocolVersion() != null) {
			sb.append(" protocol:").append(responseStatus.getProtocolVersion().toString());
		}
		sb.append(", code:").append(responseStatus.getStatusCode());
		if (responseStatus.getReasonPhrase() != null) {
			sb.append(", reasonPhrase:").append(responseStatus.getReasonPhrase());
		}

		LOG.error(sb.toString());
		return sb.toString();
	}
725225
def print_request(request):
    
    print('{}\n{}\n{}\n\n{}'.format(
        '-----------START-----------',
        request.method + ' ' + request.url,
        '\n'.join('{}: {}'.format(k, v) for k, v in request.headers.items()),
        request.body,
    ))
1147706
def _encode_request(self, request):
        """"""
        obj = request_to_dict(request, self.spider)
        return self.serializer.dumps(obj)
1109829
def get_unpacked_response_body(self, requestId, mimetype="application/unknown"):
		'''
		
		'''
		content = self.Network_getResponseBody(requestId)

		assert 'result' in content
		result = content['result']

		assert 'base64Encoded' in result
		assert 'body' in result

		if result['base64Encoded']:
			content = base64.b64decode(result['body'])
		else:
			content = result['body']

		self.log.info("Navigate complete. Received %s byte response with type %s.", len(content), mimetype)

		return {'binary' : result['base64Encoded'],  'mimetype' : mimetype, 'content' : content}
1346439
def encode_json_body(data):
    
    # support for StringIO / file - like objects
    if hasattr(data, "read"):
        return data

    response.content_type = "application/json; charset=utf-8"

    return json.dumps(
        data,
        indent=4,
        separators=(',', ': ')
    )
470471
def _write_response(self, response):
        
        status = '{} {} {}\r\n'.format(response['version'],
                                       response['code'],
                                       responses[response['code']])
        self.logger.debug("Responding status: '%s'", status.strip())
        self._write_transport(status)

        if 'body' in response and 'Content-Length' not in response['headers']:
            response['headers']['Content-Length'] = len(response['body'])

        response['headers']['Date'] = datetime.utcnow().strftime(
            "%a, %d %b %Y %H:%M:%S +0000")

        for (header, content) in response['headers'].items():
            self.logger.debug("Sending header: '%s: %s'", header, content)
            self._write_transport('{}: {}\r\n'.format(header, content))

        self._write_transport('\r\n')
        if 'body' in response:
            self._write_transport(response['body'])
353287
def get_req_resp_record(self, resp_obj):
        
        def log_print(req_resp_dict, r_type):
            msg = "\n================== {} details ==================\n".format(r_type)
            for key, value in req_resp_dict[r_type].items():
                msg += "{:<16} : {}\n".format(key, repr(value))
            logger.log_debug(msg)

        req_resp_dict = {
            "request": {},
            "response": {}
        }

        # record actual request info
        req_resp_dict["request"]["url"] = resp_obj.request.url
        req_resp_dict["request"]["method"] = resp_obj.request.method
        req_resp_dict["request"]["headers"] = dict(resp_obj.request.headers)

        request_body = resp_obj.request.body
        if request_body:
            request_content_type = lower_dict_keys(
                req_resp_dict["request"]["headers"]
            ).get("content-type")
            if request_content_type and "multipart/form-data" in request_content_type:
                # upload file type
                req_resp_dict["request"]["body"] = "upload file stream (OMITTED)"
            else:
                req_resp_dict["request"]["body"] = request_body

        # log request details in debug mode
        log_print(req_resp_dict, "request")

        # record response info
        req_resp_dict["response"]["ok"] = resp_obj.ok
        req_resp_dict["response"]["url"] = resp_obj.url
        req_resp_dict["response"]["status_code"] = resp_obj.status_code
        req_resp_dict["response"]["reason"] = resp_obj.reason
        req_resp_dict["response"]["cookies"] = resp_obj.cookies or {}
        req_resp_dict["response"]["encoding"] = resp_obj.encoding
        resp_headers = dict(resp_obj.headers)
        req_resp_dict["response"]["headers"] = resp_headers

        lower_resp_headers = lower_dict_keys(resp_headers)
        content_type = lower_resp_headers.get("content-type", "")
        req_resp_dict["response"]["content_type"] = content_type

        if "image" in content_type:
            # response is image type, record bytes content only
            req_resp_dict["response"]["content"] = resp_obj.content
        else:
            try:
                # try to record json data
                req_resp_dict["response"]["json"] = resp_obj.json()
            except ValueError:
                # only record at most 512 text charactors
                resp_text = resp_obj.text
                req_resp_dict["response"]["text"] = omit_long_data(resp_text)

        # log response details in debug mode
        log_print(req_resp_dict, "response")

        return req_resp_dict
1022167
def _format(self):
        
        self.log.debug("Formatting URLs to request")
        items = list()
        for i in range(0, self.limit, 10):
            query = '"%s" %s' % (self.domain, self.modifier)
            url = self.host + "/search?q=" + query + "&first=" + str(i)
            items.append(url)
        self.log.debug("URLs were generated")
        return items
1166975
def http_log_req(method, uri, args, kwargs):
    
    if not pyrax.get_http_debug():
        return
    string_parts = ["curl -i -X %s" % method]
    for element in args:
        string_parts.append("%s" % element)
    for element in kwargs["headers"]:
        header = "-H '%s: %s'" % (element, kwargs["headers"][element])
        string_parts.append(header)
    string_parts.append(uri)
    log = logging.getLogger("pyrax")
    log.debug("\nREQ: %s\n" % " ".join(string_parts))
    if "body" in kwargs:
        pyrax._logger.debug("REQ BODY: %s\n" % (kwargs["body"]))
    if "data" in kwargs:
        pyrax._logger.debug("REQ DATA: %s\n" % (kwargs["data"]))
713967
def _wrap_response(request, data=None, metadata=None, status=200):
        
        envelope = metadata or {}

        if data is not None:
            envelope['data'] = data

        return web.Response(
            status=status,
            content_type='application/json',
            text=json.dumps(
                envelope,
                indent=2,
                separators=(',', ': '),
                sort_keys=True))
1175911
public String getResponseString(ClientResponse response) throws Exception {
    if (debug)
      LOGGER.log(Level.INFO, "status: " + response.getStatus());
    String responseText = response.getEntity(String.class);
    if (response.getStatus() != 200) {
      handleError("status " + response.getStatus() + ":'" + responseText + "'");
    }
    return responseText;
  }
322485
def parse_multipart_data(request):
    
    return MultiPartParser(
        META=request.META,
        input_data=StringIO(request.body),
        upload_handlers=request.upload_handlers,
        encoding=request.encoding
    ).parse()
1321677
def _get_body_string(self):
        
        clen = self.content_length
        if clen > self.MEMFILE_MAX:
            raise HTTPError(413, 'Request entity too large')
        if clen < 0: clen = self.MEMFILE_MAX + 1
        data = self.body.read(clen)
        if len(data) > self.MEMFILE_MAX:  # Fail fast
            raise HTTPError(413, 'Request entity too large')
        return data
757228
private String getRequestContent(HttpRequest request, String body) {
        StringBuilder builder = new StringBuilder();
        
        builder.append(request.getMethod());
        builder.append(" ");
        builder.append(request.getURI());
        builder.append(NEWLINE);
        
        appendHeaders(request.getHeaders(), builder);
        
        builder.append(NEWLINE);
        builder.append(body);
        
        return builder.toString(); 
    }
650389
def get_request_body_chunk(self, content: bytes, closed: bool,
                               more_content: bool) -> Dict[str, Any]:
        '''
        
        '''
        return {
            'content': content,
            'closed': closed,
            'more_content': more_content
        }