请求方式:get 与post
侧重于获取资源还是发送数据、URL安全及数据量限制、字符集
post方式请求
get方式获取jsp \js\css\img、png
POST 方式获取数据
HTTP长连接是指在一个TCP长连接中发送和接收多个HTTP报文。 相应地,短连接则指发送一个HTTP请求后直接关闭TCP连接。 HTTP1.0默认使用短连接,可以在客户端HTTP报文头部添加Connection:Keep-alive启用长连接请求。 HTTP1.1默认使用长连接,可以在客户端HTTP报文头部添加Connection:Closed关闭长连接请求。 HTTP1.1的请求报文和响应报文可以没有Connection:Keep-alive报头,但仍然是长连接。
HTTP客户端设置 以基于commons-httpclient-3.0.jar为例
Integer TIME_OUT = 5 * 1000; String postUrl = http://10.1.1.12:8080/postData HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(TIME_OUT); httpClient.getHttpConnectionManager().getParams().setSoTimeout(TIME_OUT); InputStream input = new ByteArrayInputStream(postData.getBytes("UTF-8")); RequestEntity entity = new InputStreamRequestEntity(input); PostMethod post = new PostMethod(postUrl); // 选择HTTP协议版本HTTP1.1 post.getParams().setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // 显式关闭长连接 post.setRequestHeader("Connection", "Closed"); post.setRequestEntity(entity); try { // 发送POST请求 httpClient.executeMethod(post); String retCharSet = post.getResponseCharSet(); StatusLine statusLine = post.getStatusLine(); Integer statusCode = statusLine.getStatusCode(); if (statusCode == 200) { returnStr = new String(post.getResponseBodyAsString().getBytes(retCharSet), retCharSet); System.out.println("post响应: " + returnStr); System.out.println("post耗时: " + (System.currentTimeMillis() - startTime) + "(ms)"); } } finally { post.releaseConnection(); }
HTTP服务端设置 以免安装版Tomcat7为例 (1) 在conf/server.xml中设置keepAliveTimeout,表示多少毫秒后如果客户端没有新的请求则关闭当前连接。 <Connector acceptCount="1000" keepAliveTimeout="5000" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/> keepAliveTimeout默认与connectionTimeout一致。
(2) 在conf/server.xml中设置maxKeepAliveRequests,表示一个长连接最多接收多少个请求,设置为1则为关闭长连接,设置为-1表示无限制。 <Connector acceptCount="1000" maxKeepAliveRequests="1" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>