java网络编程____httpclient长连接请求长轮询



import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

/**
 * @author Administrator
 * http长连接
 */
public class HttpClientLoop {
	/**
	 * 构造请求实体
	 * @param scehme
	 * @param host
	 * @param path
	 * @param nvps
	 * @return
	 * @throws Exception
	 */
	public static URI constructURI(final String scehme,final String host, final String path,List<NameValuePair>nvps) throws Exception{
		URI uri = new URIBuilder().setScheme(scehme)
				.setHost(host)
				.setPath(path).build();
				//.setParameters(nvps).build();
		return uri;
	}
	/**
	 * http长轮询 长连接
	 * @throws Exception 
	 */
	public static void httpLongConnLoop(final String scehme,final String host, final String path,List<NameValuePair>nvps) throws Exception{
		//http默认长连接策略
		ConnectionKeepAliveStrategy directStrategy = new ConnectionKeepAliveStrategy() {
			public long getKeepAliveDuration(HttpResponse response,HttpContext context) {
				//解析response信息
				HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
				while (it.hasNext()) {
					HeaderElement element = it.nextElement();
					String key = element.getName();
					String value = element.getValue();
					// 如果头部包含timeout信息,则使用
					if (value != null && key.equalsIgnoreCase("timeout")) {
						// 超时时间设置为服务器指定的值
						return Long.parseLong(value) * 1000;
					}
				}
				// 获取主机
				HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);
				if (host.equalsIgnoreCase(target.getHostName())) {
					return 5 * 1000;
				} else {
					return 30 * 1000;
				}
			}
		};
		CloseableHttpClient client = HttpClients.custom().setKeepAliveStrategy(directStrategy).build();

		URI uri =constructURI(scehme, host, path, nvps);

		HttpPost post = new HttpPost(uri);

		try {
			CloseableHttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				System.out.println("解析结果集____:" + EntityUtils.toString(response.getEntity()));
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	//http://niuzhenxin.iteye.com/blog/2100100
	public static void main(String[] args) throws Exception {
		httpLongConnLoop("http", "niuzhenxin.iteye.com", "/blog/2100100", null);
	}
	
}

//

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我会为您介绍Java中使用CloseableHttpClient发送HTTP请求的方法。 CloseableHttpClient是Apache HttpClient库中的一个类,它提供了一种发送HTTP请求的简单方法。下面是一些基本的使用方法: 1. 创建CloseableHttpClient对象 ```java CloseableHttpClient httpClient = HttpClients.createDefault(); ``` 2. 创建HttpRequest对象 HttpRequest是一个接口,它定义了HTTP请求的各种方法和属性。在使用CloseableHttpClient发送HTTP请求之前,我们需要先创建一个HttpRequest对象。常用的HttpRequest实现类有HttpGet、HttpPost、HttpPut、HttpDelete等,具体选择哪种实现类取决于你要发送的HTTP请求的类型。 例如,我们可以创建一个HttpGet对象: ```java HttpGet httpGet = new HttpGet("http://www.example.com"); ``` 3. 执行HTTP请求 创建好HttpRequest对象之后,我们就可以使用CloseableHttpClient对象来执行HTTP请求了。执行HTTP请求的方式很简单,只需要调用CloseableHttpClient对象的execute方法,并传入HttpRequest对象即可。 例如,我们可以执行上面创建的HttpGet对象: ```java CloseableHttpResponse response = httpClient.execute(httpGet); ``` 4. 处理HTTP响应 执行HTTP请求之后,我们需要处理HTTP响应。CloseableHttpResponse是一个接口,它定义了HTTP响应的各种方法和属性。我们可以使用这些方法来获取HTTP响应的状态码、响应头、响应体等信息。 例如,我们可以获取HTTP响应的状态码: ```java int statusCode = response.getStatusLine().getStatusCode(); ``` 5. 关闭CloseableHttpClient对象 最后,我们需要关闭CloseableHttpClient对象。关闭CloseableHttpClient对象可以释放与之相关的资源,例如HTTP连接、线程等。我们可以使用CloseableHttpClient对象的close方法来关闭它。 例如: ```java httpClient.close(); ``` 以上就是使用CloseableHttpClient发送HTTP请求的基本方法。希望能对您有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值