json文本协议
json:对象-字符串-byte[] -传输-byte[]-字符串-对象
pb:对象-byte[]-传输byte[]-对象
另一个例子在:pb协议 jdk序列化协议,考虑到文章太长,放于此instead of the bottom
client:
String wholeUrl = String.format("%s?sdkappid=%d&random=%d", URL, SDKAPPID, rnd);
java.net.URL object = new URL(wholeUrl);
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
JSONObject data = new JSONObject();
JSONObject tel = new JSONObject();
tel.put("nationcode", nationCode);
String phone = phoneNumber;
tel.put("phone", phone);
data.put("type", "0");
data.put("msg", content);
String sig = stringMD5(APPKEY.concat(phone));
data.put("sig", sig);
data.put("tel", tel);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "utf-8");
wr.write(data.toString());
wr.flush();
// 显示 POST 请求返回的内容
StringBuilder sb = new StringBuilder();
int HttpResult = con.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
String line;
while ((line = br.readLine()) != null)
{
sb.append(line + "\n");
}
br.close();
JSONObject reObj = new JSONObject(sb.toString());
String res = (String)reObj.get("result");
if(!"0".equals(res)) {
System.out.println("" + sb.toString());
LOGGER.error("SmsSender::sendMsg" + "-" + phoneNumber + ","+(String)reObj.get("errmsg"));
} else {
}
} else
{
LOGGER.error("send failed and rps is: " + con.getResponseMessage());
throw new SmsException("send failed and rps is: " + con.getResponseMessage());
}
请求:
JSONObject data = new JSONObject();
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "utf-8");
wr.write(data.toString());
应答:
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
String line;
while ((line = br.readLine()) != null)
{
sb.append(line + "\n");
}
br.close();
JSONObject reObj = new JSONObject(sb.toString());
String res = (String)reObj.get("result");
server:
基于netty的http server
响应请求,读取参数:
HttpServerHandler
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
// 获取channel中的URI
Attribute<String> attr = ctx.channel().attr(AttributeMapConstant.NETTY_CHANNEL_KEY_HTTP_REQ_URI);
String uri = attr.get();
byte[] bs = new byte[msg.readableBytes()];
msg.readBytes(bs);
String json = new String(bs);
BaseReq baseReq = JSON.parseObject(json, BaseReq.class);
返回应答:
tws:
HttpServerHandler
public static void rspTws(RequestIdentity ri, BaseDto dto) {
String json = JSON.toJSONString(dto);
Channel channel = ri.getClientChannel();
if (channel != null && channel.isActive()) {
logger.info("3.返回http客户端:{},流水号:{}", json, ri.getReqId());
channel.writeAndFlush(getJsonBuffer(json))
String json = JSON.toJSONString(dto);
/**
* JSON转ByteBuf
*
* @param json
* @return
*/
private static ByteBuf getJsonBuffer(String json) {
ByteBuf buffer = Unpooled.buffer();
buffer.writeBytes(json.getBytes());
return buffer;
}
json.getBytes()
/**
* HTTP消息体编码器
* @author shane
*
*/
public class HttpBodyEncoder extends MessageToMessageEncoder<ByteBuf> {
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
out.add(HttpCreateor.buildFullHttpResponse(msg).retain());
}
}
public static FullHttpResponse buildFullHttpResponse(ByteBuf msg) {
// 返回信息
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, msg);
response.headers().set(HttpHeaderNames.CONTENT_TYPE, String.format("%s;charset=UTF-8", HttpHeaderValues.TEXT_PLAIN));
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
// 返回
return response;
}
action:
public class BodyToResponseEncoder extends MessageToMessageEncoder<ResponseMessage> {
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, ResponseMessage responseMessage, List<Object> list) throws Exception {
String json = JSON.toJSONString(responseMessage);
FullHttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,
Unpooled.wrappedBuffer(json.getBytes("utf-8")));
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json;charset=UTF-8");
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
// 下面2个支持跨域
response.headers().set(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
response.headers().set(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_HEADERS, HttpHeaders.Names.CONTENT_TYPE);
list.add(response);
}
}
String json = JSON.toJSONString(responseMessage);
json.getBytes("utf-8")
浙公网安备 33010602011771号