public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { URI uri = this.getLocationURI(request, response, context); String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) { return new HttpHead(uri); } else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) { return this.copyEntity(new HttpPost(uri), request); } else if (method.equalsIgnoreCase(HttpPut.METHOD_NAME)) { return this.copyEntity(new HttpPut(uri), request); } else if (method.equalsIgnoreCase(HttpDelete.METHOD_NAME)) { return new HttpDelete(uri); } else if (method.equalsIgnoreCase(HttpTrace.METHOD_NAME)) { return new HttpTrace(uri); } else if (method.equalsIgnoreCase(HttpOptions.METHOD_NAME)) { return new HttpOptions(uri); } else if (method.equalsIgnoreCase(HttpPatch.METHOD_NAME)) { return this.copyEntity(new HttpPatch(uri), request); } else { return new HttpGet(uri); } }
public boolean isRedirected( final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } int statusCode = response.getStatusLine().getStatusCode(); String method = request.getRequestLine().getMethod(); Header locationHeader = response.getFirstHeader("location"); switch (statusCode) { case HttpStatus.SC_MOVED_TEMPORARILY: return isRedirectable(method) && locationHeader != null; case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_TEMPORARY_REDIRECT: return isRedirectable(method); case HttpStatus.SC_SEE_OTHER: return true; default: return false; } //end of switch }
public RequestWrapper(final HttpRequest request) throws ProtocolException { super(); if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } this.original = request; setParams(request.getParams()); setHeaders(request.getAllHeaders()); // Make a copy of the original URI if (request instanceof HttpUriRequest) { this.uri = ((HttpUriRequest) request).getURI(); this.method = ((HttpUriRequest) request).getMethod(); this.version = null; } else { RequestLine requestLine = request.getRequestLine(); try { this.uri = new URI(requestLine.getUri()); } catch (URISyntaxException ex) { throw new ProtocolException("Invalid request URI: " + requestLine.getUri(), ex); } this.method = requestLine.getMethod(); this.version = request.getProtocolVersion(); } this.execCount = 0; }
/** * Handles the given exception and generates an HTTP response to be sent * back to the client to inform about the exceptional condition encountered * in the course of the request processing. * * @param ex the exception. * @param response the HTTP response. */ protected void handleException(final HttpException ex, final HttpResponse response) { if (ex instanceof MethodNotSupportedException) { response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); } else if (ex instanceof UnsupportedHttpVersionException) { response.setStatusCode(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED); } else if (ex instanceof ProtocolException) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); } else { response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); } String message = ex.getMessage(); if (message == null) { message = ex.toString(); } byte[] msg = EncodingUtils.getAsciiBytes(message); ByteArrayEntity entity = new ByteArrayEntity(msg); entity.setContentType("text/plain; charset=US-ASCII"); response.setEntity(entity); }
@Override protected URI createLocationURI(String location) throws ProtocolException { try { final URIBuilder b = new URIBuilder(new URI(encode(location)).normalize()); final String host = b.getHost(); if (host != null) { b.setHost(host.toLowerCase(Locale.ROOT)); } final String path = b.getPath(); if (TextUtils.isEmpty(path)) { b.setPath("/"); } return b.build(); } catch (final URISyntaxException ex) { throw new ProtocolException("Invalid redirect URI: " + location, ex); } }
@Override public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { URI uri = getLocationURI(request, response, context); String method = request.getRequestLine().getMethod(); if ("post".equalsIgnoreCase(method)) { try { HttpRequestWrapper httpRequestWrapper = (HttpRequestWrapper) request; httpRequestWrapper.setURI(uri); httpRequestWrapper.removeHeaders("Content-Length"); return httpRequestWrapper; } catch (Exception e) { logger.error("强转为HttpRequestWrapper出错"); } return new HttpPost(uri); } else { return new HttpGet(uri); } }
static void rewriteRequestURI( final HttpRequestWrapper request, final HttpRoute route) throws ProtocolException { try { URI uri = request.getURI(); if (uri != null) { // Make sure the request URI is relative if (uri.isAbsolute()) { uri = URIUtilsHC4.rewriteURI(uri, null, true); } else { uri = URIUtilsHC4.rewriteURI(uri); } request.setURI(uri); } } catch (final URISyntaxException ex) { throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex); } }
public boolean isRedirected( final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { Args.notNull(request, "HTTP request"); Args.notNull(response, "HTTP response"); final int statusCode = response.getStatusLine().getStatusCode(); final String method = request.getRequestLine().getMethod(); final Header locationHeader = response.getFirstHeader("location"); switch (statusCode) { case HttpStatus.SC_MOVED_TEMPORARILY: return isRedirectable(method) && locationHeader != null; case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_TEMPORARY_REDIRECT: return isRedirectable(method); case HttpStatus.SC_SEE_OTHER: return true; default: return false; } //end of switch }
/** * @since 4.1 */ protected URI createLocationURI(final String location) throws ProtocolException { try { final URIBuilder b = new URIBuilder(new URI(location).normalize()); final String host = b.getHost(); if (host != null) { b.setHost(host.toLowerCase(Locale.ENGLISH)); } final String path = b.getPath(); if (TextUtils.isEmpty(path)) { b.setPath("/"); } return b.build(); } catch (final URISyntaxException ex) { throw new ProtocolException("Invalid redirect URI: " + location, ex); } }
public HttpUriRequest getRedirect( final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { final URI uri = getLocationURI(request, response, context); final String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHeadHC4.METHOD_NAME)) { return new HttpHeadHC4(uri); } else if (method.equalsIgnoreCase(HttpGetHC4.METHOD_NAME)) { return new HttpGetHC4(uri); } else { final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_TEMPORARY_REDIRECT) { return RequestBuilder.copy(request).setUri(uri).build(); } else { return new HttpGetHC4(uri); } } }
public HttpRoute determineRoute( final HttpHost host, final HttpRequest request, final HttpContext context) throws HttpException { Args.notNull(request, "Request"); if (host == null) { throw new ProtocolException("Target host is not specified"); } final HttpClientContext clientContext = HttpClientContext.adapt(context); final RequestConfig config = clientContext.getRequestConfig(); final InetAddress local = config.getLocalAddress(); HttpHost proxy = config.getProxy(); if (proxy == null) { proxy = determineProxy(host, request, context); } final HttpHost target; if (host.getPort() <= 0) { try { target = new HttpHost( host.getHostName(), this.schemePortResolver.resolve(host), host.getSchemeName()); } catch (final UnsupportedSchemeException ex) { throw new HttpException(ex.getMessage()); } } else { target = host; } final boolean secure = target.getSchemeName().equalsIgnoreCase("https"); if (proxy == null) { return new HttpRoute(target, local, secure); } else { return new HttpRoute(target, local, proxy, secure); } }
private HttpResponse revalidateCacheEntry(final HttpHost target, final HttpRequestWrapper request, final HttpContext context, final HttpCacheEntry entry, final Date now) throws ClientProtocolException { try { if (asynchRevalidator != null && !staleResponseNotAllowed(request, entry, now) && validityPolicy.mayReturnStaleWhileRevalidating(entry, now)) { log.trace("Serving stale with asynchronous revalidation"); final HttpResponse resp = generateCachedResponse(request, context, entry, now); asynchRevalidator.revalidateCacheEntry(target, request, context, entry); return resp; } return revalidateCacheEntry(target, request, context, entry); } catch (final IOException ioex) { return handleRevalidationFailure(request, context, entry, now); } catch (final ProtocolException e) { throw new ClientProtocolException(e); } }
@Test public void testRunGracefullyHandlesProtocolException() throws Exception { final String identifier = "foo"; final AsynchronousValidationRequest impl = new AsynchronousValidationRequest( mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry, identifier, 0); when( mockClient.revalidateCacheEntry( route, request, context, mockExecAware, mockCacheEntry)).thenThrow( new ProtocolException()); impl.run(); verify(mockClient).revalidateCacheEntry( route, request, context, mockExecAware, mockCacheEntry); verify(mockParent).markComplete(identifier); verify(mockParent).jobFailed(identifier); }
static void rewriteRequestURI( final HttpRequestWrapper request, final HttpRoute route) throws ProtocolException { try { URI uri = request.getURI(); if (uri != null) { // Make sure the request URI is relative if (uri.isAbsolute()) { uri = URIUtils.rewriteURI(uri, null, true); } else { uri = URIUtils.rewriteURI(uri); } request.setURI(uri); } } catch (final URISyntaxException ex) { throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex); } }
@Override public boolean isRedirected( final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { Args.notNull(request, "HTTP request"); Args.notNull(response, "HTTP response"); final int statusCode = response.getStatusLine().getStatusCode(); final String method = request.getRequestLine().getMethod(); final Header locationHeader = response.getFirstHeader("location"); switch (statusCode) { case HttpStatus.SC_MOVED_TEMPORARILY: return isRedirectable(method) && locationHeader != null; case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_TEMPORARY_REDIRECT: return isRedirectable(method); case HttpStatus.SC_SEE_OTHER: return true; default: return false; } //end of switch }
/** * @since 4.1 */ protected URI createLocationURI(final String location) throws ProtocolException { try { final URIBuilder b = new URIBuilder(new URI(location).normalize()); final String host = b.getHost(); if (host != null) { b.setHost(host.toLowerCase(Locale.ROOT)); } final String path = b.getPath(); if (TextUtils.isEmpty(path)) { b.setPath("/"); } return b.build(); } catch (final URISyntaxException ex) { throw new ProtocolException("Invalid redirect URI: " + location, ex); } }
@Override public HttpUriRequest getRedirect( final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { final URI uri = getLocationURI(request, response, context); final String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) { return new HttpHead(uri); } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { return new HttpGet(uri); } else { final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_TEMPORARY_REDIRECT) { return RequestBuilder.copy(request).setUri(uri).build(); } else { return new HttpGet(uri); } } }
public RequestWrapper(final HttpRequest request) throws ProtocolException { super(); Args.notNull(request, "HTTP request"); this.original = request; setParams(request.getParams()); setHeaders(request.getAllHeaders()); // Make a copy of the original URI if (request instanceof HttpUriRequest) { this.uri = ((HttpUriRequest) request).getURI(); this.method = ((HttpUriRequest) request).getMethod(); this.version = null; } else { final RequestLine requestLine = request.getRequestLine(); try { this.uri = new URI(requestLine.getUri()); } catch (final URISyntaxException ex) { throw new ProtocolException("Invalid request URI: " + requestLine.getUri(), ex); } this.method = requestLine.getMethod(); this.version = request.getProtocolVersion(); } this.execCount = 0; }
@Override public HttpRoute determineRoute( final HttpHost host, final HttpRequest request, final HttpContext context) throws HttpException { Args.notNull(request, "Request"); if (host == null) { throw new ProtocolException("Target host is not specified"); } final HttpClientContext clientContext = HttpClientContext.adapt(context); final RequestConfig config = clientContext.getRequestConfig(); final InetAddress local = config.getLocalAddress(); HttpHost proxy = config.getProxy(); if (proxy == null) { proxy = determineProxy(host, request, context); } final HttpHost target; if (host.getPort() <= 0) { try { target = new HttpHost( host.getHostName(), this.schemePortResolver.resolve(host), host.getSchemeName()); } catch (final UnsupportedSchemeException ex) { throw new HttpException(ex.getMessage()); } } else { target = host; } final boolean secure = target.getSchemeName().equalsIgnoreCase("https"); if (proxy == null) { return new HttpRoute(target, local, secure); } else { return new HttpRoute(target, local, proxy, secure); } }
@Test(expected=ClientProtocolException.class) public void testRejectRelativeRedirect() throws Exception { this.serverBootstrap.registerHandler("*", new RelativeRedirectService()); final HttpHost target = start(); final RequestConfig config = RequestConfig.custom().setRelativeRedirectsAllowed(false).build(); final HttpGet httpget = new HttpGet("/oldlocation/"); httpget.setConfig(config); try { this.httpclient.execute(target, httpget); } catch (final ClientProtocolException e) { Assert.assertTrue(e.getCause() instanceof ProtocolException); throw e; } }
@Test(expected=ClientProtocolException.class) public void testRejectInvalidRedirectLocation() throws Exception { final UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); this.serverBootstrap.setHandlerMapper(reqistry); final HttpHost target = start(); reqistry.register("*", new BogusRedirectService("http://" + target.toHostString() + "/newlocation/?p=I have spaces")); final HttpGet httpget = new HttpGet("/oldlocation/"); try { this.httpclient.execute(target, httpget); } catch (final ClientProtocolException e) { Assert.assertTrue(e.getCause() instanceof ProtocolException); throw e; } }
@Test(expected=ProtocolException.class) public void testResponseParsingWithTooMuchGarbage() throws Exception { final String s = "garbage\r\n" + "garbage\r\n" + "more garbage\r\n" + "HTTP/1.1 200 OK\r\n" + "header1: value1\r\n" + "header2: value2\r\n" + "\r\n"; final SessionInputBuffer inbuffer = new SessionInputBufferMock(s, Consts.ASCII); final HttpMessageParser<HttpResponse> parser = new DefaultHttpResponseParser(inbuffer) { @Override protected boolean reject(final CharArrayBuffer line, final int count) { return count >= 2; } }; parser.parse(); }
@Override public HttpUriRequest getRedirect( final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { final URI uri = getLocationURI(request, response, context); final String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) { return new HttpHead(uri); } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { return new HttpGet(uri); } else { final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_TEMPORARY_REDIRECT || status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY) { return RequestBuilder.copy(request).setUri(uri).build(); } return new HttpGet(uri); } }
/** * @since 4.1 */ protected URI createLocationURI(final String location) throws ProtocolException { try { URI uri; //NULogger.getLogger().log(Level.INFO, "location: {0}", location); //If it contains a special char we create our custom uri (it fails otherwise) if(location.contains("|")){ uri = neembuu.uploader.utils.URIUtils.createURI(location); } else{ uri = new URI(location); } return uri.normalize(); } catch (URISyntaxException ex) { throw new ProtocolException("Invalid redirect URI: " + location, ex); } }
@Override public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { final URL metarefresh = (URL) context.getAttribute(METAREFRESH_LOCATION); if (metarefresh == null) { return super.getRedirect(request, response, context); } final String method = request.getRequestLine().getMethod(); try { if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) { return new HttpHead(metarefresh.toURI()); } else { return new HttpGet(metarefresh.toURI()); } } catch (final URISyntaxException e) { return super.getRedirect(request, response, context); } }
protected void rewriteRequestURI( final RequestWrapper request, final HttpRoute route) throws ProtocolException { try { URI uri = request.getURI(); if (route.getProxyHost() != null && !route.isTunnelled()) { // Make sure the request URI is absolute if (!uri.isAbsolute()) { HttpHost target = route.getTargetHost(); uri = URIUtils.rewriteURI(uri, target); request.setURI(uri); } } else { // Make sure the request URI is relative if (uri.isAbsolute()) { uri = URIUtils.rewriteURI(uri, null); request.setURI(uri); } } } catch (URISyntaxException ex) { throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex); } }
public RequestWrapper(final HttpRequest request) throws ProtocolException { super(); if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } this.original = request; setParams(request.getParams()); // Make a copy of the original URI if (request instanceof HttpUriRequest) { this.uri = ((HttpUriRequest) request).getURI(); this.method = ((HttpUriRequest) request).getMethod(); this.version = null; } else { RequestLine requestLine = request.getRequestLine(); try { this.uri = new URI(requestLine.getUri()); } catch (URISyntaxException ex) { throw new ProtocolException("Invalid request URI: " + requestLine.getUri(), ex); } this.method = requestLine.getMethod(); this.version = request.getProtocolVersion(); } this.execCount = 0; }
/** * @since 4.1 */ protected URI createLocationURI(final String location) throws ProtocolException { System.out.println("redirect_location:"+location); try { final URIBuilder b = new URIBuilder(new URI(location).normalize()); final String host = b.getHost(); if (host != null) { b.setHost(host.toLowerCase(Locale.ENGLISH)); } final String path = b.getPath(); if (TextUtils.isEmpty(path)) { b.setPath("/"); } return b.build(); } catch (final URISyntaxException ex) { throw new ProtocolException("Invalid redirect URI: " + location, ex); } }
public HttpUriRequest getRedirect( final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { final URI uri = getLocationURI(request, response, context); final String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) { return new HttpHead(uri); } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { return new HttpGet(uri); } else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) { return new HttpPost(uri); } else { final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_TEMPORARY_REDIRECT) { return RequestBuilder.copy(request).setUri(uri).build(); } else { return new HttpGet(uri); } } }