[#2732] HttpRequestEncoder may produce invalid uri if uri parameters are included.

Motivation:

If the requests contains uri parameters but not path the HttpRequestEncoder does produce an invalid uri while try to add the missing path.

Modifications:

Correctly handle the case of uri with paramaters but no path.

Result:

HttpRequestEncoder produce correct uri in all cases.
This commit is contained in:
Norman Maurer 2014-08-05 10:13:05 +02:00
parent cc33417c0e
commit e33f12f5b8
2 changed files with 27 additions and 2 deletions

View File

@ -26,6 +26,7 @@ import static io.netty.handler.codec.http.HttpConstants.*;
*/ */
public class HttpRequestEncoder extends HttpObjectEncoder<HttpRequest> { public class HttpRequestEncoder extends HttpObjectEncoder<HttpRequest> {
private static final char SLASH = '/'; private static final char SLASH = '/';
private static final char QUESTION_MARK = '?';
private static final byte[] CRLF = { CR, LF }; private static final byte[] CRLF = { CR, LF };
@Override @Override
@ -48,9 +49,23 @@ public class HttpRequestEncoder extends HttpObjectEncoder<HttpRequest> {
int start = uri.indexOf("://"); int start = uri.indexOf("://");
if (start != -1 && uri.charAt(0) != SLASH) { if (start != -1 && uri.charAt(0) != SLASH) {
int startIndex = start + 3; int startIndex = start + 3;
// Correctly handle query params.
// See https://github.com/netty/netty/issues/2732
int index = uri.indexOf(QUESTION_MARK, startIndex);
if (index == -1) {
if (uri.lastIndexOf(SLASH) <= startIndex) { if (uri.lastIndexOf(SLASH) <= startIndex) {
uri += SLASH; uri += SLASH;
} }
} else {
if (uri.lastIndexOf(SLASH, index) <= startIndex) {
int len = uri.length();
StringBuilder sb = new StringBuilder(len + 1);
sb.append(uri, 0, index);
sb.append(SLASH);
sb.append(uri, index, len);
uri = sb.toString();
}
}
} }
} }

View File

@ -37,6 +37,16 @@ public class HttpRequestEncoderTest {
assertEquals("GET http://localhost/ HTTP/1.1\r\n", req); assertEquals("GET http://localhost/ HTTP/1.1\r\n", req);
} }
@Test
public void testUriWithoutPath2() throws Exception {
HttpRequestEncoder encoder = new HttpRequestEncoder();
ByteBuf buffer = Unpooled.buffer(64);
encoder.encodeInitialLine(buffer, new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
"http://localhost:9999?p1=v1"));
String req = buffer.toString(Charset.forName("US-ASCII"));
assertEquals("GET http://localhost:9999/?p1=v1 HTTP/1.1\r\n", req);
}
@Test @Test
public void testUriWithPath() throws Exception { public void testUriWithPath() throws Exception {
HttpRequestEncoder encoder = new HttpRequestEncoder(); HttpRequestEncoder encoder = new HttpRequestEncoder();