1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.http;
21
22 import java.nio.ByteBuffer;
23 import java.nio.charset.CharsetEncoder;
24 import java.nio.charset.StandardCharsets;
25 import java.util.Map;
26
27 import org.apache.mina.core.buffer.IoBuffer;
28 import org.apache.mina.core.session.IoSession;
29 import org.apache.mina.filter.codec.ProtocolEncoder;
30 import org.apache.mina.filter.codec.ProtocolEncoderOutput;
31 import org.apache.mina.http.api.HttpEndOfContent;
32 import org.apache.mina.http.api.HttpRequest;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36
37
38
39
40 public class HttpClientEncoder implements ProtocolEncoder {
41 private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientCodec.class);
42 private static final CharsetEncoder ENCODER = StandardCharsets.UTF_8.newEncoder();
43
44
45
46
47 @Override
48 public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
49 if (LOGGER.isDebugEnabled()) {
50 LOGGER.debug("encode {}", message.getClass().getCanonicalName());
51 }
52
53 if (message instanceof HttpRequest) {
54 if (LOGGER.isDebugEnabled()) {
55 LOGGER.debug("HttpRequest");
56 }
57
58 HttpRequest/../../../org/apache/mina/http/api/HttpRequest.html#HttpRequest">HttpRequest msg = (HttpRequest)message;
59 StringBuilder sb = new StringBuilder(msg.getMethod().toString());
60 sb.append(" ");
61 sb.append(msg.getRequestPath());
62
63 if (!"".equals(msg.getQueryString())) {
64 sb.append("?");
65 sb.append(msg.getQueryString());
66 }
67
68 sb.append(" ");
69 sb.append(msg.getProtocolVersion());
70 sb.append("\r\n");
71
72 for (Map.Entry<String, String> header : msg.getHeaders().entrySet()) {
73 sb.append(header.getKey());
74 sb.append(": ");
75 sb.append(header.getValue());
76 sb.append("\r\n");
77 }
78
79 sb.append("\r\n");
80 IoBuffer buf = IoBuffer.allocate(sb.length()).setAutoExpand(true);
81 buf.putString(sb.toString(), ENCODER);
82 buf.flip();
83 out.write(buf);
84 } else if (message instanceof ByteBuffer) {
85 if (LOGGER.isDebugEnabled()) {
86 LOGGER.debug("Body");
87 }
88
89 out.write(message);
90 } else if (message instanceof HttpEndOfContent) {
91 if (LOGGER.isDebugEnabled()) {
92 LOGGER.debug("End of Content");
93 }
94
95
96 }
97 }
98
99
100
101
102 @Override
103 public void dispose(IoSession arg0) throws Exception {
104
105 }
106 }