android的HttpGet和HttpPost

public String doGet( String url )
{
    try
    {
        HttpGet method = new HttpGet( url );

        DefaultHttpClient client = new DefaultHttpClient();
        method.setHeader( "Connection", "Keep-Alive" );
        
        HttpResponse response = client.execute( method );
        int status = response.getStatusLine().getStatusCode();
        if ( status != HttpStatus.SC_OK )
            throw new Exception( "" );
        
        return EntityUtils.toString( response.getEntity(), "UTF-8" );
    }
    catch ( Exception e )
    {
        return null;
    }
}

public String doPost( String url, String params )
{
    try
    {            
        HttpPost method = new HttpPost( url );
        
        DefaultHttpClient client = new DefaultHttpClient();
        StringEntity paramEntity = new StringEntity( params );
        paramEntity.setChunked( false );
        paramEntity.setContentType( "application/x-www-form-urlencoded" );
        method.setEntity( paramEntity );
        
        HttpResponse response = client.execute( method );
        int status = response.getStatusLine().getStatusCode();
        if ( status != HttpStatus.SC_OK )
            throw new Exception( "" );
        
        return EntityUtils.toString( response.getEntity(), "UTF-8" );
    }
    catch ( Exception e )
    {
        return null;
    }
}


节选转载于http://gihyo.jp/dev/serial/01/androidapp/0009?page=1


你可能感兴趣的:(android的HttpGet和HttpPost)