1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.http.impl.conn;
29
30 import java.io.IOException;
31
32 import org.apache.http.annotation.ThreadSafe;
33
34 import org.apache.commons.logging.Log;
35 import org.apache.commons.logging.LogFactory;
36 import org.apache.http.HttpException;
37 import org.apache.http.HttpMessage;
38 import org.apache.http.HttpResponseFactory;
39 import org.apache.http.NoHttpResponseException;
40 import org.apache.http.ProtocolException;
41 import org.apache.http.StatusLine;
42 import org.apache.http.impl.io.AbstractMessageParser;
43 import org.apache.http.io.SessionInputBuffer;
44 import org.apache.http.message.LineParser;
45 import org.apache.http.message.ParserCursor;
46 import org.apache.http.params.HttpParams;
47 import org.apache.http.util.CharArrayBuffer;
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64 @ThreadSafe
65 public class DefaultResponseParser extends AbstractMessageParser<HttpMessage> {
66
67 private final Log log = LogFactory.getLog(getClass());
68
69 private final HttpResponseFactory responseFactory;
70 private final CharArrayBuffer lineBuf;
71 private final int maxGarbageLines;
72
73 public DefaultResponseParser(
74 final SessionInputBuffer buffer,
75 final LineParser parser,
76 final HttpResponseFactory responseFactory,
77 final HttpParams params) {
78 super(buffer, parser, params);
79 if (responseFactory == null) {
80 throw new IllegalArgumentException
81 ("Response factory may not be null");
82 }
83 this.responseFactory = responseFactory;
84 this.lineBuf = new CharArrayBuffer(128);
85 this.maxGarbageLines = getMaxGarbageLines(params);
86 }
87
88 protected int getMaxGarbageLines(final HttpParams params) {
89 return params.getIntParameter(
90 org.apache.http.conn.params.ConnConnectionPNames.MAX_STATUS_LINE_GARBAGE,
91 Integer.MAX_VALUE);
92 }
93
94 @Override
95 protected HttpMessage parseHead(
96 final SessionInputBuffer sessionBuffer) throws IOException, HttpException {
97
98 int count = 0;
99 ParserCursor cursor = null;
100 do {
101
102 this.lineBuf.clear();
103 int i = sessionBuffer.readLine(this.lineBuf);
104 if (i == -1 && count == 0) {
105
106 throw new NoHttpResponseException("The target server failed to respond");
107 }
108 cursor = new ParserCursor(0, this.lineBuf.length());
109 if (lineParser.hasProtocolVersion(this.lineBuf, cursor)) {
110
111 break;
112 } else if (i == -1 || count >= this.maxGarbageLines) {
113
114 throw new ProtocolException("The server failed to respond with a " +
115 "valid HTTP response");
116 }
117 if (this.log.isDebugEnabled()) {
118 this.log.debug("Garbage in response: " + this.lineBuf.toString());
119 }
120 count++;
121 } while(true);
122
123 StatusLine statusline = lineParser.parseStatusLine(this.lineBuf, cursor);
124 return this.responseFactory.newHttpResponse(statusline, null);
125 }
126
127 }