Read the response's HTTP status line and header fields.

        Coroutine.
778700
def read_response(self, response=None):
        '''
        '''
        _logger.debug('Reading header.')

        if response is None:
            response = Response()

        header_lines = []
        bytes_read = 0

        while True:
            try:
                data = yield from self._connection.readline()
            except ValueError as error:
                raise ProtocolError(
                    'Invalid header: {0}'.format(error)) from error

            self._data_event_dispatcher.notify_read(data)

            if not data.endswith(b'\n'):
                raise NetworkError('Connection closed.')
            elif data in (b'\r\n', b'\n'):
                break

            header_lines.append(data)
            assert data.endswith(b'\n')

            bytes_read += len(data)

            if bytes_read > 32768:
                raise ProtocolError('Header too big.')

        if not header_lines:
            raise ProtocolError('No header received.')

        response.parse(b''.join(header_lines))

        return response
75697
def read_response(self):
        ""
        try:
            response = self._parser.read_response()
        except socket.timeout:
            self.disconnect()
            raise TimeoutError("Timeout reading from %s:%s" %
                               (self.host, self.port))
        except socket.error:
            self.disconnect()
            e = sys.exc_info()[1]
            raise ConnectionError("Error while reading from %s:%s : %s" %
                                  (self.host, self.port, e.args))
        except:  # noqa: E722
            self.disconnect()
            raise
        if isinstance(response, ResponseError):
            raise response
        return response
1056538
def post_process(self, stream_to_file=False):
        
        self.status_code = self.response.status_code
        if 200 <= self.status_code < 300:
            if stream_to_file:
                self.stream_to_file(stream_to_file)
            else:
                self.extract_data()
        else:
            self._timestamps.setdefault('exception', time.time())
            if self.status_code in HTTP_STATUS_CODES:
                self.error = HTTP_STATUS_CODES[self.status_code].str_to_obj(
                    self.response.content)
            else:
                self.error = Exception('Status code = %s' % self.status_code)
            raise self.error
1309592
private InputStream readHttpHeader() throws IOException {
    	
    	// this can be helpful when simply iterating over records, 
    	// looking for problems.
        Logger logger = Logger.getLogger(this.getClass().getName());
    	ArchiveRecordHeader h = this.getHeader();
    	
        // If judged a record that doesn't have an http header, return
        // immediately.
        String url = getHeader().getUrl();
        if(!url.startsWith("http") ||
            getHeader().getLength() <= MIN_HTTP_HEADER_LENGTH) {
            return null;
        }
        
        String statusLine;
        byte[] statusBytes;
        int eolCharCount = 0;
        int errOffset = 0;
        
        // Read status line, skipping any errant http headers found before it
        // This allows a larger number of 'corrupt' arcs -- where headers were accidentally
        // inserted before the status line to be readable
        while (true) {
        	statusBytes = LaxHttpParser.readRawLine(getIn());
        	eolCharCount = getEolCharsCount(statusBytes);
        	if (eolCharCount <= 0) {
        		throw new RecoverableIOException(
                "Failed to read http status where one was expected: " 
                + ((statusBytes == null) ? "" : new String(statusBytes)));
        	}
        
        	statusLine = EncodingUtil.getString(statusBytes, 0,
        			statusBytes.length - eolCharCount, ARCConstants.DEFAULT_ENCODING);
        	
        	// If a null or DELETED break immediately
        	if ((statusLine == null) || statusLine.startsWith("DELETED")) {
        		break;
        	}
        	
        	// If it's actually the status line, break, otherwise continue skipping any
        	// previous header values
        	if (!statusLine.contains(":") && StatusLine.startsWithHTTP(statusLine)) {
        		break;
        	}
        	
        	// Add bytes read to error "offset" to add to position
        	errOffset += statusBytes.length;
        }
        
        if (errOffset > 0) {
            this.incrementPosition(errOffset);
        }
        
        if ((statusLine == null) ||
                !StatusLine.startsWithHTTP(statusLine)) {
            if (statusLine.startsWith("DELETED")) {
                // Some old ARCs have deleted records like following:
                // http://vireo.gatech.edu:80/ebt-bin/nph-dweb/dynaweb/SGI_Developer/SGITCL_PG/@Generic__BookTocView/11108%3Btd%3D2 130.207.168.42 19991010131803 text/html 29202
                // DELETED_TIME=20000425001133_DELETER=Kurt_REASON=alexalist
                // (follows ~29K spaces)
                // For now, throw a RecoverableIOException so if iterating over
                // records, we keep going.  TODO: Later make a legitimate
                // ARCRecord from the deleted record rather than throw
                // exception.
                throw new DeletedARCRecordIOException(statusLine);
            } else {
            	this.errors.add(ArcRecordErrors.HTTP_STATUS_LINE_INVALID);
            }
        }

        try {
        	this.httpStatus = new StatusLine(statusLine);
        } catch(IOException e) {
        	logger.warning(e.getMessage() + " at offset: " + h.getOffset());
        	this.errors.add(ArcRecordErrors.HTTP_STATUS_LINE_EXCEPTION);
        }
        
        // Save off all bytes read.  Keep them as bytes rather than
        // convert to strings so we don't have to worry about encodings
        // though this should never be a problem doing http headers since
        // its all supposed to be ascii.
        ByteArrayOutputStream baos =
            new ByteArrayOutputStream(statusBytes.length + 4 * 1024);
        baos.write(statusBytes);
        
        // Now read rest of the header lines looking for the separation
        // between header and body.
        for (byte [] lineBytes = null; true;) {
            lineBytes = LaxHttpParser.readRawLine(getIn());
            eolCharCount = getEolCharsCount(lineBytes);
            if (eolCharCount <= 0) {
            	if (getIn().available() == 0) {
            		httpHeaderBytesRead += statusBytes.length;
                	logger.warning("HTTP header truncated at offset: " + h.getOffset());
            		this.errors.add(ArcRecordErrors.HTTP_HEADER_TRUNCATED);
            		this.setEor(true);
            		break;
            	} else {
            		throw new IOException("Failed reading http headers: " +
            				((lineBytes != null)? new String(lineBytes): null));
            	}
            } else {
            	httpHeaderBytesRead += lineBytes.length;
            }
            // Save the bytes read.
            baos.write(lineBytes);
            if ((lineBytes.length - eolCharCount) <= 0) {
                // We've finished reading the http header.
                break;
            }
        }
        
        byte [] headerBytes = baos.toByteArray();
        // Save off where body starts.
        this.getMetaData().setContentBegin(headerBytes.length);
        ByteArrayInputStream bais =
            new ByteArrayInputStream(headerBytes);
        if (!bais.markSupported()) {
            throw new IOException("ByteArrayInputStream does not support mark");
        }
        bais.mark(headerBytes.length);
        // Read the status line.  Don't let it into the parseHeaders function.
        // It doesn't know what to do with it.
        bais.read(statusBytes, 0, statusBytes.length);
        this.httpHeaders = LaxHttpParser.parseHeaders(bais,
            ARCConstants.DEFAULT_ENCODING);
        this.getMetaData().setStatusCode(Integer.toString(getStatusCode()));
        bais.reset();
        return bais;
    }
57147
def _check_response_status(self, response):
        
        if response.status_code != requests.codes.ok:
            self._logger.error("%s %s", response.status_code, response.text)
            raise exceptions.RequestNonSuccessException(
                "Url {0} had status_code {1}".format(
                    response.url, response.status_code))
978629
def _parse_status_code(response):
    

    # This happens when a status response is expected
    if isinstance(response, string_types):
        return response

    # This happens when a list of structs are expected
    is_single_list = isinstance(response, list) and len(response) == 1
    if is_single_list and isinstance(response[0], string_types):
        return response[0]

    # This happens when a struct of any kind is returned
    return "OK"
775093
def parse(self, stream, full_statusline=None):
        

        # status line w newlines intact
        if full_statusline is None:
            full_statusline = stream.readline()

        full_statusline = self.decode_header(full_statusline)

        statusline, total_read = _strip_count(full_statusline, 0)

        headers = []

        # at end of stream
        if total_read == 0:
            raise EOFError()
        elif not statusline:
            return StatusAndHeaders(statusline=statusline,
                                    headers=headers,
                                    protocol='',
                                    total_len=total_read)

        # validate only if verify is set
        if self.verify:
            protocol_status = self.split_prefix(statusline, self.statuslist)

            if not protocol_status:
                msg = 'Expected Status Line starting with {0} - Found: {1}'
                msg = msg.format(self.statuslist, statusline)
                raise StatusAndHeadersParserException(msg, full_statusline)
        else:
            protocol_status = statusline.split(' ', 1)

        line, total_read = _strip_count(self.decode_header(stream.readline()), total_read)
        while line:
            result = line.split(':', 1)
            if len(result) == 2:
                name = result[0].rstrip(' \t')
                value = result[1].lstrip()
            else:
                name = result[0]
                value = None

            next_line, total_read = _strip_count(self.decode_header(stream.readline()),
                                                 total_read)

            # append continuation lines, if any
            while next_line and next_line.startswith((' ', '\t')):
                if value is not None:
                    value += next_line
                next_line, total_read = _strip_count(self.decode_header(stream.readline()),
                                                     total_read)

            if value is not None:
                header = (name, value)
                headers.append(header)

            line = next_line

        if len(protocol_status) > 1:
            statusline = protocol_status[1].strip()
        else:
            statusline = ''

        return StatusAndHeaders(statusline=statusline,
                                headers=headers,
                                protocol=protocol_status[0],
                                total_len=total_read)
891759
def process_response(self, result):
        
        if len(result) == 3:
            data = result[0]
            headers = result[2]
            if self.HEADER_API_VERSION in headers:
                api_version = headers[self.HEADER_API_VERSION]
                if (not self.already_printed_version_warning
                        and not self.is_up_to_date(api_version)):
                    print('Warning: Looks like you\'re using an outdated API '
                          'Version, please consider updating (server ' +
                          api_version + ' / client ' + self.__version__ + ')')
                    self.already_printed_version_warning = True
            return data
        return result
836253
def get_status_from_location(self, response):
        
        self._raise_if_bad_http_status_and_method(response)
        code = response.status_code
        if code == 202:
            self.status = "InProgress"
        else:
            self.status = 'Succeeded'
            if self._is_empty(response):
                self.resource = None
            else:
                self.resource = self._deserialize(response)
108892
public void readHeader(LineInput in) throws IOException
    {
        _state = __MSG_BAD;

        // Get start line
        org.browsermob.proxy.jetty.util.LineInput.LineBuffer line_buffer;

        do
        {
            line_buffer = in.readLineBuffer();
            if (line_buffer == null) throw new EOFException();
        }
        while (line_buffer.size == 0);

        if (line_buffer.size >= __maxLineLength)
                throw new HttpException(HttpResponse.__414_Request_URI_Too_Large);
        decodeRequestLine(line_buffer.buffer, line_buffer.size);
        _timeStamp = System.currentTimeMillis();

        // Handle version - replace with fast compare
        if (__HTTP_1_1.equals(_version))
        {
            _dotVersion = 1;
            _version = __HTTP_1_1;
            _header.read(in);
            updateMimeType();
        }
        else if (__HTTP_0_9.equals(_version))
        {
            _dotVersion = -1;
            _version = __HTTP_0_9;
        }
        else
        {
            _dotVersion = 0;
            _version = __HTTP_1_0;
            _header.read(in);
            updateMimeType();
        }

        _handled = false;
        _state = __MSG_RECEIVED;
    }
350481
def read_init_status(self):
        
        api_path = '/v1/sys/init'
        response = self._adapter.get(
            url=api_path,
        )
        return response.json()
670299
def read_response(self):
        
        response = self._read_response()
        frame, data = nsq.unpack_response(response)
        self.last_response = time.time()

        if frame not in self._frame_handlers:
            raise errors.NSQFrameError('unknown frame {}'.format(frame))

        frame_handler = self._frame_handlers[frame]
        processed_data = frame_handler(data)

        return frame, processed_data
824597
def status(self, status, headers=None):
        '''
        
        '''
        self.response = _Response(status, headers)
        return self
1295423
def ReadCompletedRequests(self, session_id, timestamp=None, limit=None):
    """"""
    subject = session_id.Add("state")
    requests = {}
    status = {}

    for predicate, serialized, _ in self.ResolvePrefix(
        subject, [self.FLOW_REQUEST_PREFIX, self.FLOW_STATUS_PREFIX],
        limit=limit,
        timestamp=timestamp):

      parts = predicate.split(":", 3)
      request_id = parts[2]
      if parts[1] == "status":
        status[request_id] = serialized
      else:
        requests[request_id] = serialized

    for request_id, serialized in sorted(iteritems(requests)):
      if request_id in status:
        yield (rdf_flow_runner.RequestState.FromSerializedString(serialized),
               rdf_flows.GrrMessage.FromSerializedString(status[request_id]))
1156974
function () {
                if (headerResponse !== null) {
                    return headerResponse;
                }
                // Read status and normalize an IE9 bug (http://bugs.jquery.com/ticket/1450).
                var status = xhr.status === 1223 ? 204 : xhr.status;
                var statusText = xhr.statusText || 'OK';
                // Parse headers from XMLHttpRequest - this step is lazy.
                var headers = new HttpHeaders(xhr.getAllResponseHeaders());
                // Read the response URL from the XMLHttpResponse instance and fall back on the
                // request URL.
                var url = getResponseUrl(xhr) || req.url;
                // Construct the HttpHeaderResponse and memoize it.
                headerResponse = new HttpHeaderResponse({ headers: headers, status: status, statusText: statusText, url: url });
                return headerResponse;
            }
278098
def start_response(self, status, headers, exc_info = None):
    """"""
    if self.started_response:
      if not exc_info:
        raise AssertionError("WSGI start_response called a second "
                   "time with no exc_info.")
      else:
        try:
          raise exc_info[0], exc_info[1], exc_info[2]
        finally:
          exc_info = None
    self.started_response = True
    self.status = status
    self.outheaders.extend(headers)

    return self.write_buffer.write
664645
@Override
    protected void readResponseHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException {
        getResponseHeaderGroup().clear();

        Header[] headers = ZapHttpParser.parseHeaders(conn.getResponseInputStream(), getParams().getHttpElementCharset());
        // Wire logging moved to HttpParser
        getResponseHeaderGroup().setHeaders(headers);
    }