提交 487859df 编写于 作者: S shenhongxi

http+protobuf

上级 7a7dbcc0
......@@ -30,6 +30,22 @@
<artifactId>grpc-stub</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-core</artifactId>
<version>2.0.16</version>
</dependency>
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-integration-beans</artifactId>
<version>2.0.16</version>
<exclusions>
<exclusion>
<groupId>org.apache.mina</groupId>
<artifactId>mina-core</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
......
package com.itlong.whatsmars.http;
import com.itlong.whatsmars.grpc.service.HelloResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by shenhongxi on 2017/6/14.
*/
public class Demo {
public static void main(String[] args) {
}
public static String post(String url, byte[] args, String requestName) throws Exception {
String result = null;
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Request-Name", requestName);
conn.setConnectTimeout(30 * 1000);
conn.setReadTimeout(30 * 1000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(args);
os.close();
if (200 == conn.getResponseCode()) {
InputStream in = conn.getInputStream();
byte[] bytes1 = new byte[conn.getContentLength()];
in.read(bytes1);
HelloResponse orderResponse = HelloResponse.parseFrom(bytes1);
result = orderResponse.toString();
}
conn.disconnect();
return result;
}
}
package com.itlong.whatsmars.http;
import java.util.HashMap;
import java.util.Map;
public abstract class HttpMessage {
String version = "HTTP/1.1";
String messageBody = "";
Map<String, String> messageHeader = new HashMap();
public String getVersion()
{
return this.version;
}
public void setVersion(String version) {
this.version = version;
}
public String getMessageBody() {
return this.messageBody;
}
public void setMessageBody(String messageBody) {
this.messageBody = messageBody;
}
public Map<String, String> getMessageHeader() {
return this.messageHeader;
}
public void setMessageHeader(Map<String, String> messageHeader) {
this.messageHeader = messageHeader;
}
public String getRequestHeader(String key) {
return (String)this.messageHeader.get(key);
}
public void addRequestHeader(String key, String value) {
this.messageHeader.put(key, value);
}
}
package com.itlong.whatsmars.http;
import com.itlong.whatsmars.grpc.service.HelloRequest;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import java.util.Arrays;
/**
* Created by shenhongxi on 2017/6/14.
*/
public class HttpRequestDecoder extends CumulativeProtocolDecoder {
@Override
protected boolean doDecode(IoSession ioSession, IoBuffer ioBuffer, ProtocolDecoderOutput out) throws Exception {
int start = ioBuffer.position();
String content = "";
byte[] messages = null;
try {
//content = inBuffer.getString(Charset.forName("UTF-8").newDecoder());
messages = new byte[ioBuffer.limit()];
ioBuffer.get(messages);
content = new String(messages,"UTF-8");
} catch (Exception e) {
ioBuffer.position(start);
return false;
}
int position = content.indexOf("\r\n\r\n");
if (position == -1) {
ioBuffer.position(start);
return false;
}
HttpRequestMessage reqMsg = new HttpRequestMessage();
String headerContent = content.substring(0, position);
int headerLength = position + 4;
String[] headers = headerContent.split("\r\n");
for (String header : headers) {
String[] temps = header.split(": ");
if (temps == null || temps.length <= 1)
continue;
reqMsg.addRequestHeader(temps[0].trim().toLowerCase(), temps[1].trim());
}
int fLPosition = headerContent.indexOf("\r\n");
String url = headerContent.substring(0, fLPosition);
String[] urls = url.split(" ");
if (urls.length < 3) {
reqMsg.setErrorCode(400);
out.write(reqMsg);
return true;
}
if (!"GET".equalsIgnoreCase(urls[0]) && !"POST".equalsIgnoreCase(urls[0])) {
reqMsg.setErrorCode(400);
out.write(reqMsg);
return true;
}
reqMsg.setRequestProtocol(urls[0]);
reqMsg.setRequestUrl(urls[1]);
reqMsg.setVersion(urls[2]);
String bodyLengthStr = reqMsg.getRequestHeader("Content-Length".toLowerCase());
if (bodyLengthStr == null) {
reqMsg.setErrorCode(400);
out.write(reqMsg);
return true;
}
int bodyLength = -1;
try {
bodyLength = Integer.parseInt(bodyLengthStr.trim());
} catch (Exception e) {
reqMsg.setErrorCode(400);
out.write(reqMsg);
return true;
}
String bodyContent = null;
int packageLength = bodyLength + headerLength;
if (content.getBytes("UTF-8").length >= packageLength) {
ioBuffer.position(packageLength);
int l = messages.length;
byte[] bodyBytes = Arrays.copyOfRange(messages, headerLength, packageLength);
String requestName = reqMsg.getRequestHeader("Request-Name".toLowerCase());
if (requestName != null && !requestName.equals("")) {
if (requestName.equals("hello")) {
HelloRequest helloRequest = HelloRequest.parseFrom(bodyBytes);
}
} else {
bodyContent = new String(bodyBytes, "UTF-8");
}
} else {
ioBuffer.position(start);
return false;
}
reqMsg.setMessageBody(bodyContent);
out.write(reqMsg);
return true;
}
}
package com.itlong.whatsmars.http;
import java.util.Iterator;
import java.util.Map.Entry;
public class HttpRequestMessage extends HttpMessage
{
private String requestProtocol;
private String requestUrl;
private int errorCode = 0;
public int getErrorCode() {
return this.errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String getRequestProtocol() {
return this.requestProtocol;
}
public void setRequestProtocol(String requestProtocol) {
this.requestProtocol = requestProtocol;
}
public String getRequestUrl() {
return this.requestUrl;
}
public void setRequestUrl(String requestUrl) {
this.requestUrl = requestUrl;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("\r\n\r\n");
sb.append("\r\n");
sb.append(this.requestProtocol).append(" ").append(this.requestUrl).append(" ").append(this.version).append("\r\n");
Iterator iterator = this.messageHeader.entrySet().iterator();
while (iterator.hasNext()) {
Entry entry = (Entry)iterator.next();
sb.append((String)entry.getKey()).append(": ").append((String)entry.getValue()).append("\r\n");
}
sb.append("\r\n\r\n");
sb.append(this.messageBody);
sb.append("\r\n\r\n");
return sb.toString();
}
}
package com.itlong.whatsmars.http;
import com.itlong.whatsmars.grpc.service.HelloResponse;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Iterator;
import java.util.Map;
public class HttpResponseEncoder extends ProtocolEncoderAdapter
{
private static Logger logger = LoggerFactory.getLogger(HttpResponseEncoder.class);
public void encode(IoSession iosession, Object obj, ProtocolEncoderOutput out) throws Exception {
HttpResponseMessage respMsg = (HttpResponseMessage)obj;
String requestName = respMsg.getMessageHeader().get("Request-Name");
if (requestName != null && !requestName.equals("")) {
byte[] bytes = null;
if (requestName.equals("hello")) {
HelloResponse.Builder response = HelloResponse.newBuilder();
bytes = response.build().toByteArray();
}
StringBuilder sb = new StringBuilder();
sb.append(respMsg.getVersion()).append(" ").append(respMsg.getStatusCode()).append(" ").append(respMsg.getStatusMessage()).append("\r\n");
Iterator iterator = respMsg.getMessageHeader().entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry)iterator.next();
sb.append((String)entry.getKey()).append(": ").append((String)entry.getValue()).append("\r\n");
}
sb.append("Content-Length").append(": ").append(bytes.length);
sb.append("\r\n\r\n");
byte[] headBytes = sb.toString().getBytes("UTF-8");
logger.debug("#############################[响应请求解析完毕]###############################");
IoBuffer buf = IoBuffer.allocate(headBytes.length + bytes.length, false);
buf.setAutoExpand(true);
buf.put(headBytes);
buf.put(bytes);
buf.flip();
out.write(buf);
} else {
StringBuilder sb = new StringBuilder();
sb.append(respMsg.getVersion()).append(" ").append(respMsg.getStatusCode()).append(" ").append(respMsg.getStatusMessage()).append("\r\n");
Iterator iterator = respMsg.getMessageHeader().entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry)iterator.next();
sb.append((String)entry.getKey()).append(": ").append((String)entry.getValue()).append("\r\n");
}
sb.append("Content-Length").append(": ").append(respMsg.getContentLength());
sb.append("\r\n\r\n");
sb.append(respMsg.getMessageBody());
if (logger.isDebugEnabled()) {
String msg = respMsg != null ? respMsg.toString() : "";
if (!msg.contains("<html") && !msg.contains("<HTML")) {
logger.debug("resp:{}", respMsg);
}
logger.debug("#############################[响应请求解析完毕]###############################");
}
IoBuffer buf = IoBuffer.allocate(sb.toString().length(), false);
buf.setAutoExpand(true);
buf.put(sb.toString().getBytes("UTF-8"));
buf.flip();
out.write(buf);
}
}
}
package com.itlong.whatsmars.http;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map.Entry;
public class HttpResponseMessage extends HttpMessage
{
private static Logger logger = LoggerFactory.getLogger(HttpResponseMessage.class);
private int statusCode = 200;
private String statusMessage = "OK";
public HttpResponseMessage()
{
this.messageHeader.put("Content-Type", "text/json; charset=UTF-8");
}
public int getStatusCode()
{
return this.statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getStatusMessage() {
return this.statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
public byte[] getByteBody() throws UnsupportedEncodingException {
if (this.messageBody == null) {
return new byte[0];
}
return this.messageBody.getBytes("UTF-8");
}
public int getContentLength() throws UnsupportedEncodingException {
if (this.messageBody == null) {
return 0;
}
return this.messageBody.getBytes("UTF-8").length;
}
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("\r\n\r\n");
sb.append("\r\n");
sb.append("HTTP/1.1").append(" ").append(200).append(" ").append(this.statusMessage).append("\r\n");
Iterator iterator = this.messageHeader.entrySet().iterator();
while (iterator.hasNext()) {
Entry entry = (Entry)iterator.next();
sb.append((String)entry.getKey()).append(": ").append((String)entry.getValue()).append("\r\n");
}
try
{
sb.append("Content-Length").append(": ").append(String.valueOf(getContentLength()));
}
catch (Exception e) {
logger.error("Encoding Error!", e);
}
sb.append("\r\n\r\n");
sb.append(this.messageBody);
sb.append("\r\n\r\n");
return sb.toString();
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册