View Javadoc
1   package org.apache.mina.http;
2   
3   import java.nio.ByteBuffer;
4   import java.nio.charset.Charset;
5   import java.nio.charset.CharsetEncoder;
6   import java.util.Map;
7   
8   import org.apache.mina.core.buffer.IoBuffer;
9   import org.apache.mina.core.session.IoSession;
10  import org.apache.mina.filter.codec.ProtocolEncoder;
11  import org.apache.mina.filter.codec.ProtocolEncoderOutput;
12  import org.apache.mina.http.api.HttpEndOfContent;
13  import org.apache.mina.http.api.HttpRequest;
14  import org.slf4j.Logger;
15  import org.slf4j.LoggerFactory;
16  
17  public class HttpClientEncoder implements ProtocolEncoder {
18      private static final Logger LOG = LoggerFactory.getLogger(HttpClientCodec.class);
19      private static final CharsetEncoder ENCODER = Charset.forName("UTF-8").newEncoder();
20  
21  	public void encode(IoSession session, Object message, ProtocolEncoderOutput out)
22  			throws Exception {
23  		LOG.debug("encode {}", message.getClass().getCanonicalName());
24  		if (message instanceof HttpRequest) {
25  			LOG.debug("HttpRequest");
26  			HttpRequest msg = (HttpRequest)message;
27  			StringBuilder sb = new StringBuilder(msg.getMethod().toString());
28  			sb.append(" ");
29  			sb.append(msg.getRequestPath());
30  			if (!"".equals(msg.getQueryString())) {
31  				sb.append("?");
32  				sb.append(msg.getQueryString());
33  			}
34  			sb.append(" ");
35  			sb.append(msg.getProtocolVersion());
36  			sb.append("\r\n");
37  
38  			for (Map.Entry<String, String> header : msg.getHeaders().entrySet()) {
39                  sb.append(header.getKey());
40                  sb.append(": ");
41                  sb.append(header.getValue());
42                  sb.append("\r\n");
43              }
44              sb.append("\r\n");
45              // Java 6 >> byte[] bytes = sb.toString().getBytes(Charset.forName("UTF-8"));
46              // byte[] bytes = sb.toString().getBytes();
47              // out.write(ByteBuffer.wrap(bytes));
48              IoBuffer buf = IoBuffer.allocate(sb.length()).setAutoExpand(true);
49              buf.putString(sb.toString(), ENCODER);
50              buf.flip();
51              out.write(buf);
52          } else if (message instanceof ByteBuffer) {
53          	LOG.debug("Body");
54          	out.write(message);
55          } else if (message instanceof HttpEndOfContent) {
56          	LOG.debug("End of Content");
57              // end of HTTP content
58              // keep alive ?
59  		}
60  
61  	}
62  
63  	public void dispose(IoSession arg0) throws Exception {
64  		// TODO Auto-generated method stub
65  
66  	}
67  
68  }