使用JavaSocket编写发送HTTP_POST请求的工具类 (四)

2014-11-24 11:39:21 · 作者: · 浏览: 49
//注意:如果超时时间设为0,则表示永远不会超时
socket.connect(new InetSocketAddress(host, port), 30000);
/**
* 构造HTTP请求报文
*/
reqMsg.append("POST ").append(sendURL.getPath()).append(" HTTP/1.1\r\n");
reqMsg.append("Cache-Control: no-cache\r\n");
reqMsg.append("Pragma: no-cache\r\n");
reqMsg.append("User-Agent: JavaSocket/").append(System.getProperty("java.version")).append("\r\n");
reqMsg.append("Host: ").append(sendURL.getHost()).append("\r\n");
reqMsg.append("Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2\r\n");
reqMsg.append("Connection: keep-alive\r\n");
reqMsg.append("Content-Type: application/x-www-form-urlencoded; charset=").append(reqCharset).append("\r\n");
reqMsg.append("Content-Length: ").append(reqData.getBytes().length).append("\r\n");
reqMsg.append("\r\n");
reqMsg.append(reqData);
/**
* 发送HTTP请求
*/
out = socket.getOutputStream();
//这里针对getBytes()补充一下:之所以没有在该方法中指明字符集(包括上面头信息组装Content-Length的时候)
//是因为传进来的请求正文里面不会含中文,而非中文的英文字母符号等等,其getBytes()无论是否指明字符集,得到的都是内容一样的字节数组
//所以更建议不要直接调用本方法,而是通过sendPostRequest(String, Map, String)间接调用本方法
//sendPostRequest(.., Map, ..)在调用本方法前,会自动对请求参数值进行URLEncoder(注意不包括key=value中的'key=')
//而该方法的第三个参数reqCharset只是为了拼装HTTP请求头信息用的,目的是告诉服务器使用哪种字符集解码HTTP请求报文里面的中文信息
out.write(reqMsg.toString().getBytes());
/**
* 接收HTTP响应
*/
in = socket.getInputStream();
//事实上就像JDK的API所述:Closing a ByteArrayOutputStream has no effect
//查询ByteArrayOutputStream.close()的源码会发现,它没有做任何事情,所以其close()与否是无所谓的
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
byte[] buffer = new byte[512];
int len = -1;
while((len=in.read(buffer)) != -1){
//将读取到的字节写到ByteArrayOutputStream中
//所以最终ByteArrayOutputStream的字节数应该等于HTTP响应报文的整体长度,而大于HTTP响应正文的长度
bytesOut.write(buffer, 0, len);
}
//响应的原始字节数组
byte[] respBuffer = bytesOut.toByteArray();
respMsgHex = formatToHexStringWithASCII(respBuffer);
/**
* 获取Content-Type中的charset值(Content-Type: text/html; charset=GBK)
*/
int from = 0;
int to = 0;
for(int i=0; i if((respBuffer[i]==99||respBuffer[i]==67) && (respBuffer[i+1]==111||respBuffer[i+1]==79) && (respBuffer[i+2]==110||respBuffer[i+2]==78) && (respBuffer[i+3]==116||respBuffer[i+3]==84) && (respBuffer[i+4]==101||respBuffer[i+4]==69) && (respBuffer[i+5]==110||respBuffer[i+5]==78) && (respBuffer[i+6]==116||respBuffer[i+6]==84) && respBuffer[i+7]==45 && (respBuffer[i+8]==84||respBuffer[i+8]==116) && (respBuffer[i+9]==121||respBuffer[i+9]==89) && (respBuffer[i+10]==112||respBuffer[i+10]==80) && (respBuffer[i+11]==101||respBuffer[i+11]==69)){
from = i;
//既然匹配到