//该方法用于设定连接时间,延迟,带宽的相对重要性(该方法的三个参数表示网络传输数据的3项指标)
//connectionTime--该参数表示用最少时间建立连接
//latency---------该参数表示最小延迟
//bandwidth-------该参数表示最高带宽
//可以为这些参数赋予任意整数值,这些整数之间的相对大小就决定了相应参数的相对重要性
//如这里设置的就是---最高带宽最重要,其次是最小连接时间,最后是最小延迟
socket.setPerformancePreferences(2, 1, 3);
/**
* 连接服务端
*/
//客户端的Socket构造方法请求与服务器连接时,可能要等待一段时间
//默认的Socket构造方法会一直等待下去,直到连接成功,或者出现异常
//若欲设定这个等待时间,就要像下面这样使用不带参数的Socket构造方法,单位是毫秒
//若超过下面设置的30秒等待建立连接的超时时间,则会抛出SocketTimeoutException
//注意:如果超时时间设为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请求
*/
//这里针对getBytes()补充一下:之所以没有在该方法中指明字符集(包括上面头信息组装Content-Length的时候)
//是因为传进来的请求正文里面不会含中文,而非中文的英文字母符号等等,其getBytes()无论是否指明字符集,得到的都是内容一样的字节数组
//所以更建议不要直接调用本方法,而是通过sendPostRequest(String, Map
//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
from = i;
/