Anrdoid 使用HttpUrlConnection发送支持http、https的post请求

Android开发的网络框架有很多,很好用也很强大,但对于与一些轻量级的项目框架就显得太大了,这里自己封装一个简单的支持http和https的网络请求工具
这里定义一个接口用来处理回调
public interface HttpCallBackListener
{
// 网络请求成功
void onFinish( String response );

// 网络请求失败
void onError( Exception e );
}
//用于在子线程和主线程的数据交换
public class ResponseCallBack< T >
{
Handler mHandler;

public ResponseCallBack(
Context context,
final HttpCallBackListener listener )
{
Looper looper = context.getMainLooper();
mHandler = new Handler( looper )
{
@Override
public void handleMessage( Message msg )
{
super.handleMessage( msg );
if( msg.what == 0 )
{
//成功
listener.onFinish( msg.obj.toString() );
}
else if( msg.what == 1 )
{
//失败
listener.onError( ( Exception )msg.obj );
}
}
};
}

public void doSuccess( T response )
{
Message message = Message.obtain();
message.obj = response;
message.what = 0;
mHandler.sendMessage( message );
}

public void doFail( Exception e )
{
Message message = Message.obtain();
message.obj = e;
message.what = 1;
mHandler.sendMessage( message );
}
}
/**
*
* HttpURLConnection 网络请求工具类
* 支持http、https
* 数据的请求都是基于HttpURLConnection的 请求成功与失败的回调都是在主线程
*/

public class HttpsUtil
{
static ExecutorService threadPool = Executors.newCachedThreadPool();

public static HttpURLConnection getSSLConn( String urlStr ) throws IOException, NoSuchAlgorithmException, KeyManagementException
{
TrustManager[] trustAllCerts = new TrustManager[ 1 ];
TrustManager tm = new SSLTrustManager();
trustAllCerts[ 0 ] = tm;
SSLContext sc = SSLContext.getInstance( “SSL” );
sc.init( null, trustAllCerts, null );
URL url = new URL( urlStr );
HttpURLConnection conn = ( HttpURLConnection )url.openConnection();
boolean useHttps = urlStr.startsWith( “https” );
if( useHttps )
{
HttpsURLConnection https = ( HttpsURLConnection )conn;
https.setSSLSocketFactory( sc.getSocketFactory() );
https.setHostnameVerifier( ( HostnameVerifier )tm );
return https;
}
return conn;
}

/**
* POST方法 返回数据会解析成字符串String
* @param context 上下文
* @param urlString 请求的url
* @param listener 回调监听
* @param params 请求参数为map集合
*/
public static void doPost(
final Context context,
final String urlString,
final HttpCallBackListener listener,
final Map< String, Object > params )
{
final StringBuffer out = new StringBuffer();
// 组织请求参数
for( String key : params.keySet() )
{
if( out.length() != 0 )
{
out.append( “&” );
}
out.append( key ).append( “=” ).append( params.get( key ) );
}
// 因为网络请求是耗时操作,所以需要另外开启一个线程来执行该任务。
threadPool.execute( new Runnable()
{
@Override
public void run()
{
URL url;
HttpURLConnection conn = null;
try
{
conn = getSSLConn( urlString );
conn.setRequestProperty( “accept”, “/” );
conn.setRequestProperty( “connection”, “Keep-Alive” );
conn.setRequestProperty( “Content-Type”, “application/x-javascript; charset=UTF-8” );
conn.setRequestProperty( “Content-Length”, String.valueOf( out.length() ) );
conn.setRequestMethod( “POST” );
conn.setConnectTimeout( 5000 );
conn.setReadTimeout( 8000 );
// 设置运行输入
conn.setDoInput( true );
// 设置运行输出
conn.setDoOutput( true );
PrintWriter printWriter = new PrintWriter( conn.getOutputStream() );
// 发送请求参数
printWriter.write( out.toString() );
// flush输出流的缓冲
printWriter.flush();
printWriter.close();

           if( conn.getResponseCode() == 200 )
           {
              // 获取网络的输入流
              InputStream is = conn.getInputStream();
              BufferedReader bf = new BufferedReader( new InputStreamReader( is, "UTF-8" ) );
              //最好在将字节流转换为字符流的时候 进行转码
              StringBuffer buffer = new StringBuffer();
              String line = "";
              while( ( line = bf.readLine() ) != null )
              {
                 buffer.append( line );
              }
              bf.close();
              is.close();
              new ResponseCallBack( context, listener ).doSuccess( buffer.toString() );
           }
           else
           {
              new ResponseCallBack( context, listener ).doFail( new NetworkErrorException( "response err code:" + conn.getResponseCode() ) );
           }
        }
        catch( MalformedURLException e )
        {
           if( listener != null )
           {
              // 回调onError()方法
              new ResponseCallBack( context, listener ).doFail( e );
           }
        }
        catch( IOException e )
        {
           if( listener != null )
           {
              // 回调onError()方法
              new ResponseCallBack( context, listener ).doFail( e );
           }
        }
        catch( NoSuchAlgorithmException e )
        {
           if( listener != null )
           {
              // 回调onError()方法
              new ResponseCallBack( context, listener ).doFail( e );
           }
        }
        catch( KeyManagementException e )
        {
           if( listener != null )
           {
              // 回调onError()方法
              new ResponseCallBack( context, listener ).doFail( e );
           }
        }
        finally
        {
           if( conn != null )
           {
              // 最后记得关闭连接
              conn.disconnect();
           }
        }
     }
  } );

}

/**
* POST方法 返回数据会解析成字符串String
* @param context 上下文
* @param urlString 请求的url
* @param listener 回调监听
* @param jsonStr 请求参数为json格式的字符串
*/
public static void doPost(
final Context context,
final String urlString,
final HttpCallBackListener listener,
final String jsonStr )
{
// 因为网络请求是耗时操作,所以需要另外开启一个线程来执行该任务。
threadPool.execute( new Runnable()
{
@Override
public void run()
{
HttpURLConnection conn = null;
try
{
byte[] data = jsonStr.getBytes();
conn = getSSLConn( urlString );
conn.setRequestProperty( “accept”, “/” );
conn.setRequestProperty( “Content-Type”, “application/x-javascript; charset=UTF-8” );
conn.setRequestProperty( “connection”, “Keep-Alive” );
conn.setRequestProperty( “Content-Length”, String.valueOf( data.length ) );
conn.setRequestMethod( “POST” );
conn.setConnectTimeout( 5000 );
conn.setReadTimeout( 8000 );
// 设置运行输入
conn.setDoInput( true );
// 设置运行输出
conn.setDoOutput( true );
OutputStream outStream = conn.getOutputStream();
outStream.write( data );
outStream.flush();
outStream.close();
if( conn.getResponseCode() == 200 )
{
// 获取网络的输入流
InputStream is = conn.getInputStream();
BufferedReader bf = new BufferedReader( new InputStreamReader( is, “UTF-8” ) );
//最好在将字节流转换为字符流的时候 进行转码
StringBuffer buffer = new StringBuffer();
String line = “”;
while( ( line = bf.readLine() ) != null )
{
buffer.append( line );
}
bf.close();
is.close();
new ResponseCallBack( context, listener ).doSuccess( buffer.toString() );
}
else
{
new ResponseCallBack( context, listener ).doFail( new NetworkErrorException( “response err code:” + conn.getResponseCode() ) );
}
}
catch( MalformedURLException e )
{
if( listener != null )
{
// 回调onError()方法
new ResponseCallBack( context, listener ).doFail( e );
}
}
catch( IOException e )
{
if( listener != null )
{
// 回调onError()方法
new ResponseCallBack( context, listener ).doFail( e );
}
}
catch( NoSuchAlgorithmException e )
{
if( listener != null )
{
// 回调onError()方法
new ResponseCallBack( context, listener ).doFail( e );
}
}
catch( KeyManagementException e )
{
if( listener != null )
{
// 回调onError()方法
new ResponseCallBack( context, listener ).doFail( e );
}
}
finally
{
if( conn != null )
{
// 最后记得关闭连接
conn.disconnect();
}
}
}
} );
}

static class SSLTrustManager implements TrustManager, X509TrustManager, HostnameVerifier
{

  @Override
  public boolean verify(
        String hostname,
        SSLSession session )
  {
     //允许所有主机
     return true;
  }

  @Override
  public void checkClientTrusted(
        X509Certificate[] chain,
        String authType ) throws CertificateException
  {
     return;
  }

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

  @Override
  public X509Certificate[] getAcceptedIssuers()
  {
     return new X509Certificate[ 0 ];
  }

  public boolean isServerTrusted(
        X509Certificate[] certs )
  {
     return true;
  }

  public boolean isClientTrusted(
        X509Certificate[] certs )
  {
     return true;
  }

}
}

猜你喜欢

转载自blog.csdn.net/believeinbelieve/article/details/53289965
今日推荐