天天看點

Android使用Apache HttpClient發送GET、POST支援https的請求

雖然HttpClient早已被廢棄了,公司的項目仍然一直使用的開源組織pache的包,下面來說一下使用HttpClient的使用步驟:
           

1,建立HttpClient對象

2,如果要發送GET請求,建立HttpGet對象;如果是POST請求,則建立HttpPost對象。

3,如果需要添加參數,對于HttpGet直接在構造URL的時候填入參數。對于POST請求,使用setEntity(HttpEntity entity)方法來設定

4,調用HttpClient對象的execute(HttpUriRequest request)發送請求,此方法傳回一個HttpResponse

5,調用HttpResponse的getALLHeaders()、getHeaders(String name)等方法可擷取伺服器響應頭;調用HttpResponse的getEntity()方法可擷取HttpEntity對象,該對象包裝了伺服器響應内容。

目前想使用Apache的包,有兩種方法

1,使用android api小于23,因為在android 6.0及以後谷歌已經廢棄Apache的包

2,在build.gradle檔案中配置

defaultConfig {

useLibrary ‘org.apache.http.legacy’

}

下面是使用代碼

public class HttpsClientUtil

{

private static HttpClient httpClient;

public static ResultEntity postByHttps(

String url,

String data )

{

HttpResponse response = null;

ResultEntity resultEntity = new ResultEntity();

try

{

byte[] byteData = data.getBytes();//byte位元組傳上送

ByteArrayEntity entity = new ByteArrayEntity( byteData );

HttpPost httpPost = new HttpPost( url );

httpPost.setEntity( entity );

HttpClient httpClient = creatHttpsClient();

response = httpClient.execute( httpPost );

if( response != null )

{

resultEntity.responseCode = response.getStatusLine().getStatusCode();

HttpEntity httpEntity = response.getEntity();

byte[] resultData = EntityUtils.toByteArray( httpEntity );

String resultStr = new String( resultData );

if( resultStr != null )

{

resultEntity.content = resultStr;

resultEntity.exception = null;

}

}

else

{

resultEntity.content = null;

resultEntity.exception = new Exception( ” respone is null” );

}

}

catch( Exception e )

{

if( response != null )

{

resultEntity.responseCode = response.getStatusLine().getStatusCode();

}

resultEntity.exception = e;

}

return resultEntity;

}

public static synchronized HttpClient creatHttpsClient()

{

if( httpClient == null )

{

try

{

HttpParams params = new BasicHttpParams();

// 設定一些基本參數

HttpProtocolParams.setVersion( params, HttpVersion.HTTP_1_1 );

HttpProtocolParams.setContentCharset( params, HTTP.UTF_8 );

HttpProtocolParams.setUseExpectContinue( params, true );

HttpProtocolParams.setUserAgent( params, “Android 2.2.1” );

// 逾時設定

ConnManagerParams.setTimeout( params, 30000 );

HttpConnectionParams.setConnectionTimeout( params, 30000 );

HttpConnectionParams.setSoTimeout( params, 30000 );

KeyStore trustStore = null;

trustStore = KeyStore.getInstance( KeyStore.getDefaultType() );

trustStore.load( null, null );

SSLSocketFactory sf = new MySSLSocketFactory( trustStore );

SchemeRegistry schReg = new SchemeRegistry();

schReg.register( new Scheme( “http”, PlainSocketFactory.getSocketFactory(), 80 ) );

// schReg.register( new Scheme( “https”, SSLSocketFactory.getSocketFactory(), 443 ) );

schReg.register( new Scheme( “https”, sf, 443 ) );

// 使用線程安全的連接配接管理來建立HttpClient

ClientConnectionManager conMgr = new ThreadSafeClientConnManager( params, schReg );

httpClient = new DefaultHttpClient( conMgr, params );

}

catch( KeyStoreException e )

{

e.printStackTrace();

}

catch( CertificateException e )

{

e.printStackTrace();

}

catch( NoSuchAlgorithmException e )

{

e.printStackTrace();

}

catch( IOException e )

{

e.printStackTrace();

}

catch( UnrecoverableKeyException e )

{

e.printStackTrace();

}

catch( KeyManagementException e )

{

e.printStackTrace();

}

}

return httpClient;

}

public static class ResultEntity

{

public int responseCode;

public Exception exception;

public String content;

}

private static class MySSLSocketFactory extends SSLSocketFactory

{

SSLContext sslContext = SSLContext.getInstance( “TLS” );

public MySSLSocketFactory( KeyStore truststore ) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException
  {
     super( truststore );
     TrustManager tm = new X509TrustManager()
     {
        public void checkClientTrusted(
              X509Certificate[] chain,
              String authType ) throws CertificateException
        {
        }

        public void checkServerTrusted(
              X509Certificate[] chain,
              String authType ) throws CertificateException
        {
        }

        public X509Certificate[] getAcceptedIssuers()
        {
           return null;
        }
     };
     sslContext.init( null, new TrustManager[]{ tm }, null );
  }

  @Override
  public Socket createSocket(
        Socket socket,
        String host,
        int port,
        boolean autoClose ) throws IOException, UnknownHostException
  {
     return sslContext.getSocketFactory().createSocket( socket, host, port, autoClose );
  }

  @Override
  public Socket createSocket() throws IOException
  {
     return sslContext.getSocketFactory().createSocket();
  }
           

}