1. 程式人生 > >httpClient例子詳解

httpClient例子詳解

package com.xf.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import javax.net.ssl.SSLException;

import org.apache.http.Consts;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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.client.utils.URIUtils;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.ConnectionRequest;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

public class HttpClientDeno {

  
  public static void main(String[] args) {
    
    try {
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  
  
  
  
  
  
  /**
   * 測試1: 構建複雜uri,這種方式會很方便的設定多個引數;
   * 
   * HttpClients類是client的具體一個實現類;
   * 
   * URIBuilder包含:協議,主機名,埠(可選),資源路徑,和多個引數(可選)
   * 
   */
  private static void test1() {
    
    CloseableHttpClient client = HttpClients.createDefault();
    
    URI uri = null;
    try {
      uri = new URIBuilder()
      .setScheme("http")
      .setHost("webservice.webxml.com.cn")
      .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")
      .setParameter("", "")//這裡可以設定多個引數
      .setParameter("", "")
      .setParameter("", "")
      .setParameter("", "")
      .build();
    } catch (URISyntaxException e1) {
      e1.printStackTrace();
    }
    
    //http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo
    HttpGet get = new HttpGet(uri);
    try {
      CloseableHttpResponse response = client.execute(get);
      
      if(response.getStatusLine().getStatusCode()==200){
        
        
        System.out.println(EntityUtils.toString(response.getEntity()));
        
        //以下這種方式讀取流也可以,只不過用EntityUtils會更方便
        /*InputStream is = response.getEntity().getContent();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len=-1;
        while((len = is.read(buffer))!=-1){
          os.write(buffer,0,len);
        }
        os.close();
        is.close();
        System.out.println(os.size()+new String(os.toByteArray(),"utf-8"));*/
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  
  
  /**
   * 為uri進行加密,並進行表單提交;
   * 
   * 許多應用需要模擬提交的HTML表單的處理,例如,在
    為了登入到Web應用程式或提交的輸入資料。 HttpClient提供的實體類
    UrlEncodedFormEntity可以實現該過程;
   */
  private static void test2(){
    
    CloseableHttpClient client = HttpClients.createDefault();
    
    HttpPost httppost = new HttpPost("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo");
    
    //構建請求引數
    List<NameValuePair> list = new ArrayList<NameValuePair>();
    list.add(new BasicNameValuePair("mobileCode", "110"));
    list.add(new BasicNameValuePair("userID", ""));

    //構建url加密實體,並以utf-8方式進行加密;
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, Consts.UTF_8);
    httppost.setEntity(entity);
    
    try {
      CloseableHttpResponse response = client.execute(httppost);
      
      if(response.getStatusLine().getStatusCode()==200){
        
        //org.apache.http.util.EntityUtils類可以快速處理伺服器返回實體物件
        System.out.println(EntityUtils.toString(response.getEntity()));
        
      }
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  
  }
  
  
  /**
   * 以回撥方式處理返回結果
   * 
   *  處理響應的最簡單和最方便的方法是通過使用ResponseHandler的
    介面。使用者不必擔心連線管理的問題。當使用一個
    ResponseHandler的時候,無論是否請求執行成功或導致異常,HttpClient將會自動釋放連線。
   */
  private static void test3(){
    
    CloseableHttpClient client = HttpClients.createDefault();
    
    //==============================================================
    ResponseHandler<Object> handler = new ResponseHandler<Object>() {
      @Override
      public Object handleResponse(final HttpResponse response) throws IOException {
        
        HttpEntity entity = response.getEntity();
        
        if (entity == null) {
          throw new ClientProtocolException("返回結果為空");
        }
      
        if(response.getStatusLine().getStatusCode()==200){
          
          //獲取返回結果的字符集 如:utf-8  gbk,並以這種字符集來讀取流資訊
          ContentType contentType = ContentType.getOrDefault(entity);
          Charset charset = contentType.getCharset();
          
          InputStreamReader reader = new InputStreamReader(entity.getContent(), charset);
          BufferedReader br = new BufferedReader(reader);
          StringBuffer sb = new StringBuffer();
          char[] buffer = new char[1024];
          while (br.read(buffer)!=-1) {
            sb.append(new String(buffer));
          }
          
          return sb.toString();
        }
        
        return null;
        
      }
    };
    //===================================================================
    
    URI uri = null;//構建uri實體
    try {
      uri = new URIBuilder()
      .setScheme("http")
      .setHost("webservice.webxml.com.cn")
      .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")
      .setParameter("", "")
      .setParameter("", "")
      .setParameter("", "")
      .build();
      
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }
    
    HttpPost post = new HttpPost(uri);
    
    try {
      
      //handler回撥
       Object obj = client.execute(post, handler);
       
       System.out.println("返回結果:"+obj);
      
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    
  }
  
  
  
  /**
   * 	設定長連線策略,根據伺服器的約束或者客戶端的約束來設定長連線的時長;
   */
  private static void test4() {
    
	  ConnectionKeepAliveStrategy strategy = new DefaultConnectionKeepAliveStrategy() {
      
	      /**
	       * 伺服器端配置(以tomcat為例):keepAliveTimeout=60000,表示在60s內內,伺服器會一直保持連線狀態。
	       * 也就是說,如果客戶端一直請求伺服器,且間隔未超過60s,則該連線將一直保持,如果60s內未請求,則超時。
	       * 
	       * getKeepAliveDuration返回超時時間;
	       */
	      @Override
	      public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
	    	  	//如果伺服器指定了超時時間,則以伺服器的超時時間為準
		        HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
		        while (it.hasNext()) {
		          HeaderElement he = it.nextElement();
		          String param = he.getName();
		          String value = he.getValue();
		          if (value != null && param.equalsIgnoreCase("timeout")) {
		            try {
		              System.out.println("伺服器指定的超時時間:" + value + " 秒");
		              return Long.parseLong(value) * 1000;
		            } catch (NumberFormatException ignore) {
		              ignore.printStackTrace();
		            }
		          }
		        }
	            
	            long keepAlive = super.getKeepAliveDuration(response, context);
	        
	            // 如果伺服器未指定超時時間,則客戶端預設30s超時
		        if (keepAlive == -1) {
		          keepAlive = 30 * 1000;
		        }
		            
		        return keepAlive;
	            
	            /*如果訪問webservice.webxml.com.cn主機,則超時時間5秒,其他主機超時時間30秒
	            HttpHost host = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);
	            if ("webservice.webxml.com.cn".equalsIgnoreCase(host.getHostName())) {
	            	keepAlive =  10 * 1000;
	            } else {
	            	keepAlive =  30 * 1000;
	            }*/
	            
	            
	      	}
		};
    
	    CloseableHttpClient client = HttpClients.custom().setKeepAliveStrategy(strategy).build();
	    
	    URI uri = null;//構建uri實體
	    try {
	      uri = new URIBuilder()
	      .setScheme("http")
	      .setHost("webservice.webxml.com.cn")
	      .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")
	      .setParameter("", "")
	      .build();
	      
	    } catch (URISyntaxException e) {
	      e.printStackTrace();
	    }
	    
	    HttpPost post = new HttpPost(uri);
	    
	    try {
	      CloseableHttpResponse response =  client.execute(post);
	      if(response.getStatusLine().getStatusCode()==200){
		     String result = EntityUtils.toString(response.getEntity());
		     System.out.println("返回的結果====="+result);
	      }
	      
	    } catch (ClientProtocolException e) {
	      e.printStackTrace();
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
    
  }
  
  
  /**
   * 構建複雜請求體
   * 
   * RequestConfig將會儲存在context上下文中,並會在連續的請求中進行傳播(來自官方文件);
   * 
   */
  private void test5(){

    CloseableHttpClient client = HttpClients.createDefault();
    
    //構建請求配置
    RequestConfig config = RequestConfig.
        custom().
        setSocketTimeout(1000*10).
        setConnectTimeout(1000*10).
        build();
    //==============================================================
    ResponseHandler<Object> handler = new ResponseHandler<Object>() {//回撥
      @Override
      public Object handleResponse(final HttpResponse response) throws IOException {
        
        HttpEntity entity = response.getEntity();
        
        if (entity == null) {
          throw new ClientProtocolException( "返回結果為空");
        }
      
        if(response.getStatusLine().getStatusCode()==200){
          ContentType contentType = ContentType.getOrDefault(entity);
          Charset charset = contentType.getCharset();
          
          InputStreamReader reader = new InputStreamReader(entity.getContent(), charset);
          BufferedReader br = new BufferedReader(reader);
          StringBuffer sb = new StringBuffer();
          char[] buffer = new char[1024];
          while (br.read(buffer)!=-1) {
            sb.append(new String(buffer));
          }
          
          return sb.toString();
        }
        
        return null;
        
      }
    };
    //===================================================================
    
    URI uri = null;
    try {
      uri = new URIBuilder()
      .setScheme("http")
      .setHost("webservice.webxml.com.cn")
      .setPath("/WebServices/MobileCodeWS.asmx/getDatabaseInfo")
      .setParameter("", "")
      .setParameter("", "")
      .setParameter("", "")
      .build();
      
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }
    
    HttpPost post = new HttpPost(uri);
    
    post.setConfig(config);//設定請求配置
    
    try {
       Object obj = client.execute(post, handler);
       
       System.out.println("返回結果:"+obj);
      
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    
  
  }
  
  
  
  /**
   *  異常恢復機制:
   *  
   *  HttpRequestRetryHandler連線失敗後,可以針對相應的異常進行相應的處理措施;
   *  HttpRequestRetryHandler介面須要使用者自己實現;
   *  
   */
  private static  void test6(){

    HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
      
      /**
       * exception異常資訊;
       * executionCount:重連次數;
       * context:上下文
       */
      @Override
      public boolean retryRequest(IOException exception, int executionCount,HttpContext context) {

        System.out.println("重連線次數:"+executionCount);
        
        if (executionCount >= 5) {//如果連線次數超過5次,就不進行重複連線
          return false;
        }
        if (exception instanceof InterruptedIOException) {//io操作中斷
          return false;
        }
        if (exception instanceof UnknownHostException) {//未找到主機
          // Unknown host
          return false;
        }
        if (exception instanceof ConnectTimeoutException) {//連線超時
          return true;
        }
        if (exception instanceof SSLException) {
          // SSL handshake exception
          return false;
        }
        HttpClientContext clientContext = HttpClientContext.adapt(context);
        
        HttpRequest request = clientContext.getRequest();
        
        boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
        
        if (idempotent) {
          // Retry if the request is considered idempotent
          return true;
        }
        return false;
      }
    };
    
    
    CloseableHttpClient client = HttpClients.custom().setRetryHandler(retryHandler).build();
    
    RequestConfig config = RequestConfig.
        custom().
        setSocketTimeout(1000*10).
        setConnectTimeout(1000*10).
        build();
    
    HttpPost post = new HttpPost("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo");
    
    post.setConfig(config);
    
    try {
      HttpResponse response = client.execute(post);
      HttpEntity entity = response.getEntity();
      
      ContentType contentType = ContentType.getOrDefault(entity);
      Charset charset = contentType.getCharset();

      InputStreamReader reader = new InputStreamReader(entity.getContent(), charset);
      BufferedReader br = new BufferedReader(reader);
      StringBuffer sb = new StringBuffer();
      char[] buffer = new char[1024];
      while (br.read(buffer) != -1) {
        sb.append(new String(buffer));
      }

      System.out.println("返回的結果:"+sb.toString());

    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    
  }
  
  
  /**
   * 	HTTP請求過濾器,在執行請求之前攔截HttpRequest 和 HttpContext;
   */
  private static void test7() throws ClientProtocolException, IOException{
    
    HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() {
      /**
       * 處理請求:
       * 如果是客戶端:這個處理在傳送請求之前執行;
       * 如果是伺服器:這個處理在接收到請求體之前執行;
       */
      public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
        AtomicInteger count = (AtomicInteger) context.getAttribute("count");
        request.addHeader("count", Integer.toString(count.getAndIncrement()));
      }
    };
    
    
    CloseableHttpClient httpclient = HttpClients.
            custom().
            addInterceptorLast(requestInterceptor).
            build();
    
    
    AtomicInteger count = new AtomicInteger(1);
    HttpClientContext context = HttpClientContext.create();
    context.setAttribute("count", count);
    HttpGet httpget = new HttpGet("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo");
    
    for (int i = 0; i < 10; i++) {
      CloseableHttpResponse response = httpclient.execute(httpget,context);
      try {
        
        HttpEntity entity = response.getEntity();
//				System.out.println(EntityUtils.toString(entity));
        
      } finally {
        response.close();
      }
    }
  }
  
  /**
   * 
   *  	httpclient會自動處理重定向; 
   *  
   * 	301 永久重定向,告訴客戶端以後應從新地址訪問.
    	302 作為HTTP1.0的標準,以前叫做Moved Temporarily ,現在叫Found. 現在使用只是為了相容性的  處理,包括PHP的預設Location重定向用的也是302.
    	但是HTTP 1.1 有303 和307作為詳細的補充,其實是對302的細化
    	303:對於POST請求,它表示請求已經被處理,客戶端可以接著使用GET方法去請求Location裡的URI。
    	307:對於POST請求,表示請求還沒有被處理,客戶端應該向Location裡的URI重新發起POST請求。
   */
  private static void test8() throws ClientProtocolException, IOException,URISyntaxException {
	    LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy();
	    CloseableHttpClient httpclient = HttpClients.custom().setRedirectStrategy(redirectStrategy).build();
	
	    HttpClientContext context = HttpClientContext.create();
	    HttpGet httpget = new HttpGet("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo");
	    CloseableHttpResponse response = httpclient.execute(httpget, context);
	    try {
		  HttpHost target = context.getTargetHost();
		  List<URI> redirectLocations = context.getRedirectLocations();
		  URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
		  System.out.println("Final HTTP location: " + location.toASCIIString());
	    } finally {
	      response.close();
	    }
  }
  
  
}

相關推薦

httpClient例子

package com.xf.httpclient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.I

css權重問題例子

tro gree id選擇器 紅色 詳解 one 描述 ren ace 首先,id選擇器權重級別最高,class選擇器其次,html選擇器最後。 例子: <div class="t1" id="one"> <div class="t2" id="t

sed命令例子

moved 輸入 size 字母轉 amp sep def cde family sed -e ‘/Patricia/h‘ -e ‘/Margot/x‘ datafile    包含Margot的行將被包含Patricia的行替換; sed -e /WE/{h;d;}‘ -

awk命令例子

劃線 pan $1 空格 led 部分 分隔 線表 模式 awk -F: ‘{print "Number of dields: "NF}‘ passwd        字段分隔符設為冒號,所以每條記錄的字段數變成7; awk ‘{print "Number of diel

Asp.Net MVC WebAPI的建立與前臺Jquery ajax後臺HttpClient呼叫 Asp.Net中對操作Sql Server 簡單處理的SqlDB類

1、什麼是WebApi,它有什麼用途?           Web API是一個比較寬泛的概念。這裡我們提到Web API特指ASP.NET MVC Web API。在新出的MVC中,增加了WebAPI,用於提供REST風格的WebService,新生成的W

HttpClient` 原始碼之`UrlEncodedFormEntity

HttpClient 原始碼詳解之UrlEncodedFormEntity 1. 類釋義 /** * An entity composed of a list of url-encoded pairs. * This is typically useful while sen

HttpClient 原始碼之 BasicNameValuePair

HttpClient 原始碼詳解之 BasicNameValuePair 1. 類定義 Basic implementation of {@link NameValuePair}. 2. 方法簡介 構造器 /** * Default C

HttpClient 原始碼之HttpEntity

HttpClient 原始碼詳解 之HttpEntity 1. 類釋義 An entity that can be sent or received with an HTTP message. Entities can be found in some requests

HttpClient 原始碼之HttpRequestBase

HttpClient 原始碼詳解之HttpRequestBase 1. 類釋義 * Base implementation of {@link HttpUriRequest}. 2. 基本方法 getURI() 返回初始的請求URI【這個URI不會隨著重定位或者請

考研 演算法【資料結構】時間複雜度的計算 配套例子

【資料結構】時間複雜度的計算  配套例子詳解 一、什麼是演算法: 演算法(Algorithm)是指解題方案的準確而完整的描述,是一系列解決問題的清晰指令,演算法代表著用系統的方法描述解決問題的策略機制。 演算法的特徵: 一個演算法應該具有以下五個重要的特徵: 有

HttpServlet使用小例子:HelloServlet

小白一名,搞了2小時終於搞懂怎麼使用HttpServlet,下面是一個最簡單的小例子: 首先必須要在MyEclipse正確配置tomcat,這是前提,可以輸入localhost確認: 可以開啟tomcat頁面,就表示配置好了 然後建立一個WebProject專案 這裡我已經建

java反射例子

1、通過一個物件獲得完整的包名和類名 Java程式碼   package Reflect;  /**  * 通過一個物件獲得完整的包名和類名  * */class Demo{      //other codes...}  class hello{      publ

HttpClient使用(MultipartEntityBuilder 上傳檔案等)

Http協議的重要性相信不用我多說了,HttpClient相比傳統JDK自帶的URLConnection,增加了易用性和靈活性(具體區別,日後我們再討論),它不僅是客戶端傳送Http請求變得容易,而且也方便了開發人員測試介面(基於Http協議的),即提高了開發的效率,

SCALA的例子

scala是一門函式式的面向物件的語言,它執行在java虛擬機器上。 eg1、 示例程式碼: scala>var helloWorld = "hello" + " world"  println(helloWorld)scala>val again = " ag

HttpClient使用(轉)

Http協議的重要性相信不用我多說了,HttpClient相比傳統JDK自帶的URLConnection,增加了易用性和靈活性(具體區別,日後我們再討論),它不僅是客戶端傳送Http請求變得容易,而且也方便了開發人員測試介面(基於Http協議的),即提高了開發的效率,

Skynet基礎入門例子(5)

Socket通訊協議Sproto 在和客戶端通訊時,需要制訂一套通訊協議。 skynet 並沒有規定任何通訊協議,所以你可以自由選擇。 sproto 是一套由 skynet 自身提供的協議,並沒有特別推薦使用,只是一個選項。sproto 有一個獨立專案存在

Servlet檔案下載例子及response的contentType型別大全

一、Servlet檔案下載例子。 以下例子為實現檔案下載的工具方法, package com.avcon.utils; import java.io.File; import java.io.FileInputStream; impor

httpclient使用(爬蟲)

一、簡介 HttpClient是Apache Jakarta Common下的子專案,用來提供高效的、最新的、功能豐富的支援HTTP協議的客戶端程式設計工具包,並且它支援HTTP協議最新的版本和建議。HttpClient已經應用在很多的專案中,比如Apache Jaka

Apache HttpClient使用

轉載地址:http://eksliang.iteye.com/blog/2191017 Http協議的重要性相信不用我多說了,HttpClient相比傳統JDK自帶的URLConnection,增加了易用性和靈活性(具體區別,日後我們再討論),它不僅是客戶端傳送Http請求變得容易,而且也方便了開發人

h.264 CAVLC例子

表3歸納成公式levelCode = 2*level-2(level>0),  levelCode=-2*level-1 (level<0) (1)對於係數1。 由表3,levelCode = 2*level-2 = 2*1-2 = 0 參照h.264標準9.2.2。 因為 !(TotalC