本文主要介绍了Servlet如何接受HttpCilent发送过来的请求以及对请求进行回复
Servlet需要用到Servlet-api.jar包
package com.firstdata.project;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.ListIterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Test {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String origRequestMsg = null;
byte[] reqBuf = null;
try {
InputStream is = req.getInputStream();
reqBuf = readInputBytes(is);
origRequestMsg = new String(reqBuf, "GBK");
System.out.println(origRequestMsg);
} catch (Exception e) {
e.printStackTrace();
}
// 出来完收到信息之后可以就可以回复请求了
try {
OutputStream os = res.getOutputStream();
String resMsgOut = "this is response message";
os.write(resMsgOut.getBytes("GBK"));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* reads input stream passed and populates bytes
*
* @param is
* InputStream
* @return byte[]
* @throws IOException
*/
private byte[] readInputBytes(InputStream is) throws IOException {
ArrayList<ByteCountObj> inputByteList = new ArrayList<ByteCountObj>();
byte[] inBuf = new byte[2000];
int coutRead = is.read(inBuf);
while (coutRead != -1) {
ByteCountObj obj = new ByteCountObj(inBuf, coutRead);
inputByteList.add(obj);
inBuf = new byte[2000];
coutRead = is.read(inBuf);
}
coutRead = 0;
ListIterator<ByteCountObj> it = inputByteList.listIterator();
while (it.hasNext()) {
ByteCountObj ob = it.next();
coutRead += ob.getByteCount();
}
ByteBuffer byteBuf = ByteBuffer.allocate(coutRead);
it = inputByteList.listIterator();
while (it.hasNext()) {
ByteCountObj ob = it.next();
coutRead = ob.getByteCount();
inBuf = ob.getByteBuf();
byteBuf.put(inBuf, 0, coutRead);
}
if (byteBuf.hasArray()) {
return byteBuf.array();
} else {
return null;
}
}
/**
* 用来储存获取到的byte[]以及字节流的长度
*
* @author
*
*/
public class ByteCountObj {
private byte[] byteBuf;
private int byteCount;
public byte[] getByteBuf() {
return byteBuf;
}
public int getByteCount() {
return byteCount;
}
public ByteCountObj(byte[] byteBuf, int byteCount) {
this.byteBuf = byteBuf;
this.byteCount = byteCount;
}
}
}