使用jetty 自带的http client!

转自:http://iamrunning.iteye.com/blog/405444

一般情况下我们需要使用HttpClient时可供选择的技术有: 
1、HttpURLConnection 
2、Apache HttpClient 
其他的除了写Socket 我都没有用过了。 

偶然的机会发现Jetty 里面也自带了一个HttpClient,并且支持事件触发的处理方式。 

HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL);
try
{
  client.start();
}
catch (Exception e)
{
  throw new ServletException(e);
}

// create the exchange object, which lets you define where you want to go
// and what you want to do once you get a response
ContentExchange exchange = new ContentExchange()
{
  // define the callback method to process the response when you get it back
  protected void onResponseComplete() throws IOException
  {
    super.onResponseComplete();
    String responseContent = this.getResponseContent();

    // do something with the response content
    ...
  }
};

exchange.setMethod("GET");
exchange.setURL("http://www.example.com/");

// start the exchange
client.send(exchange);

 

 

public static void main(String[] args) throws Exception {
		HttpClient httpClient = new HttpClient();
		// set up httpClient
		httpClient.start();
		ContentExchange contentExchange = new ContentExchange();
		httpClient.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL);
		contentExchange.setURL("http://www.iteye.com");
		httpClient.send(contentExchange);
		contentExchange.waitForDone();
		System.err.println("Response status: "
				+ contentExchange.getResponseStatus());
		byte[] responseContentBytes = contentExchange.getResponseContentBytes();
		System.out.println(new String (responseContentBytes,"UTF-8"));
	}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值