net/http HTTPResponse status

本文详细介绍了Ruby中Net模块下的HTTP请求与响应类层次结构。涵盖了从HTTP基本请求方法如GET、POST到复杂的响应状态如200 OK、404 Not Found等各类HTTP交互流程中的关键类。
ruby 代码
 
  1. # Here is HTTP request class hierarchy.  
  2.  #  
  3.  #   Net::HTTPRequest  
  4.  #       Net::HTTP::Get  
  5.  #       Net::HTTP::Head  
  6.  #       Net::HTTP::Post  
  7.  #       Net::HTTP::Put  
  8.  #       Net::HTTP::Proppatch  
  9.  #       Net::HTTP::Lock  
  10.  #       Net::HTTP::Unlock  
  11.  #       Net::HTTP::Options  
  12.  #       Net::HTTP::Propfind  
  13.  #       Net::HTTP::Delete  
  14.  #       Net::HTTP::Move  
  15.  #       Net::HTTP::Copy  
  16.  #       Net::HTTP::Mkcol  
  17.  #       Net::HTTP::Trace  
  18.  #  
  19.  # === HTTP Response Classes  
  20.  #  
  21.  # Here is HTTP response class hierarchy.  
  22.  # All classes are defined in Net module.  
  23.  #  
  24.  #   HTTPResponse  
  25.  #       HTTPUnknownResponse  
  26.  #       HTTPInformation                    # 1xx  
  27.  #           HTTPContinue                       # 100  
  28.  #           HTTPSwitchProtocl                  # 101  
  29.  #       HTTPSuccess                        # 2xx  
  30.  #           HTTPOK                             # 200  
  31.  #           HTTPCreated                        # 201  
  32.  #           HTTPAccepted                       # 202  
  33.  #           HTTPNonAuthoritativeInformation    # 203  
  34.  #           HTTPNoContent                      # 204  
  35.  #           HTTPResetContent                   # 205  
  36.  #           HTTPPartialContent                 # 206  
  37.  #       HTTPRedirection                    # 3xx  
  38.  #           HTTPMultipleChoice                 # 300  
  39.  #           HTTPMovedPermanently               # 301  
  40.  #           HTTPFound                          # 302  
  41.  #           HTTPSeeOther                       # 303  
  42.  #           HTTPNotModified                    # 304  
  43.  #           HTTPUseProxy                       # 305  
  44.  #           HTTPTemporaryRedirect              # 307  
  45.  #       HTTPClientError                    # 4xx  
  46.  #           HTTPBadRequest                     # 400  
  47.  #           HTTPUnauthorized                   # 401  
  48.  #           HTTPPaymentRequired                # 402  
  49.  #           HTTPForbidden                      # 403  
  50.  #           HTTPNotFound                       # 404  
  51.  #           HTTPMethodNotAllowed               # 405  
  52.  #           HTTPNotAcceptable                  # 406  
  53.  #           HTTPProxyAuthenticationRequired    # 407  
  54.  #           HTTPRequestTimeOut                 # 408  
  55.  #           HTTPConflict                       # 409  
  56.  #           HTTPGone                           # 410  
  57.  #           HTTPLengthRequired                 # 411  
  58.  #           HTTPPreconditionFailed             # 412  
  59.  #           HTTPRequestEntityTooLarge          # 413  
  60.  #           HTTPRequestURITooLong              # 414  
  61.  #           HTTPUnsupportedMediaType           # 415  
  62.  #           HTTPRequestedRangeNotSatisfiable   # 416  
  63.  #           HTTPExpectationFailed              # 417  
  64.  #       HTTPServerError                    # 5xx  
  65.  #           HTTPInternalServerError            # 500  
  66.  #           HTTPNotImplemented                 # 501  
  67.  #           HTTPBadGateway                     # 502  
  68.  #           HTTPServiceUnavailable             # 503  
  69.  #           HTTPGatewayTimeOut                 # 504  
  70.  #           HTTPVersionNotSupported            # 505  
  71.    
  72.  # == Switching Net::HTTP versions  
@Slf4j @Component("relayPostRequestDataProcessor") public class RelayPostRequestDataProcessor<T extends PostRequestChannel> extends PostRequestDataProcessor<T> { @Override protected DataProcessState processData(T postChannel, DataProcessState dataProcessState, IHttpData data) { if (dataProcessState == DataProcessState.TRANSMIT_DIRECT) { return super.transmitDataDirectly(postChannel, DataProcessState.TRANSMIT_DIRECT, data); } else if (dataProcessState == DataProcessState.WANT_RESPONSE_MOULD) { return processHttpResponseMould(postChannel, data); } else { // Use direct transmission as default action. This case should not happen. return super.transmitDataDirectly(postChannel, DataProcessState.TRANSMIT_DIRECT, data); } } /** * Parse the response mould into response header, set it into POST request channel and transmit it to all GET * request channels related with the POST request channel. * * @param postChannel The POST request channel which received the response mould data. * @param data The response mould data */ protected DataProcessState processHttpResponseMould(T postChannel, IHttpData data) throws IllegalRequestException { log.debug("[sid:{}] Process first data: index={}", postChannel.getSid(), data.getIndex()); try { String content = null; if (data instanceof MultipartHttpData) { content = ((MultipartHttpData) data).addedContents().toString(data.getContentCharset()); } else { content = data.toString(); } HttpResponse httpResponse = parseHttpResponse(content); // If the Transfer-Encoding: chunked is set, do not modified as Chunked is used to measure the message // length of the HTTP response even if the Content-Length is set at the same time. if (!HttpUtil.isTransferEncodingChunked(httpResponse)) { String type = postChannel.getInformation().getParams().get(RelayConsts.ParamKey.TYPE); if (RelayConsts.Type.FILE.equals(type)) { // If the type is file, the Content-Length field in response should be the file size and multipart // should not be used. if (postChannel.getInformation().getContentType().isMultiPart() && httpResponse.headers().contains(HttpHeaderNames.CONTENT_LENGTH)) { throw new IllegalRequestException( "file type with multipart package should use Transfer-Encoding: chunked."); } } else { // If the type is other value, only when the Content-Length field in response does not exist or is // negtive, new Content-Length will be set. if (HttpUtil.getContentLength(httpResponse, -1L) < 0) { long contentLength = HttpUtil.getContentLength(postChannel.getInformation().getOrignalRequest(), -1L); httpResponse.headers().set(RelayConsts.HttpNames.CONTENT_LENGTH, contentLength > 0 ? contentLength : Long.MAX_VALUE); } } } // if status is 429, it shows device has too many relay connections at the same time // if (postChannel.hasSegmenter() && // httpResponse.status().code() == HttpResponseStatus.TOO_MANY_REQUESTS.code()) { // postChannel.stopSegmenterWhenCanNotGetVideoStream(RelayConsts.SegmenterStopReason.RELAY_CONNECTION_EXCEEDED); // } postChannel.setResponseHeader(httpResponse); postChannel.transmitHttpResponse(httpResponse); return postChannel.changeToNextState(); } finally { data.release(); } } /** * Parse response header from {@link String} format to {@link HttpResponse} format. * * @param stringValue {@link String} format of response header. * * @return {@link HttpResponse} format of response header. */ public HttpResponse parseHttpResponse(String stringValue) throws IllegalRequestException { String[] parts = stringValue.split("\r\n", 2); if (parts.length != 2 || parts[1].isEmpty()) { throw new IllegalRequestException("Invalid first data as a response header: " + stringValue); } String[] statusLine = parts[0].split(" ", 3); if (statusLine.length != 3 || statusLine[1].isEmpty() || statusLine[2].isEmpty()) { throw new IllegalRequestException("Invalid first data with an invalid response line: " + parts[0]); } HttpResponse httpResponse = null; try { HttpResponseStatus status = new SpecificCodeHttpResponseStatus(statusLine[1], statusLine[2]); httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status); } catch (NumberFormatException e) { throw new IllegalRequestException("Invalid first data with an unresovled status code: " + parts[0]); } String[] entries = parts[1].split("\r\n"); for (String entry : entries) { String[] content = entry.split(":", 2); if (content.length != 2 || content[1].isEmpty()) { throw new IllegalRequestException("Invalid first data with an unresovled header: " + entry); } String name = content[0].trim(); String value = content[1].trim(); if (name.isEmpty()) { throw new IllegalRequestException("Invalid first data with an empty key of header:" + entry); } httpResponse.headers().add(name, value); } // Netty channel of GET could not be reused. httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); httpResponse.headers().set(HttpHeaderNames.PRAGMA, HttpHeaderValues.NO_CACHE); httpResponse.headers().set(HttpHeaderNames.CACHE_CONTROL, HttpHeaderValues.NO_CACHE); return httpResponse; } }
最新发布
09-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值