通常狀況下咱們須要使用HttpClient時可供選擇的技術有:
一、HttpURLConnection
二、Apache HttpClient
其餘的除了寫Socket 我都沒有用過了。
偶然的機會發現Jetty 裏面也自帶了一個HttpClient,而且支持事件觸發的處理方式。 javascript
- 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"));
- }