Android使用Apache HttpClient发送GET、POST支持https的请求

安卓笔记 专栏收录该内容
17 篇文章 0 订阅
 虽然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();
  }

}

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值